gpt4 book ai didi

typescript - 如何获取数组中的常见类型

转载 作者:行者123 更新时间:2023-12-05 05:30:13 25 4
gpt4 key购买 nike

我有结构

interface T1<T extends string> {
path: T,
handler: (value: T) => void
};

如果我使用具有相同接口(interface)的函数,我对类型没有任何问题,一切都是正确的

declare function foo1<T extends string>({ path, handler }: T1<T>): void

const handlerWithoutError = (v: 'some_path') => { }
foo1({ path: 'some_path', handler: handlerWithoutError })

const handlerWithError = (v: 'wrong_path') => { }
foo1({ path: 'other_path', handler: handlerWithError })

但如果我尝试使用数组而不是明显的接口(interface),则该类型会以错误的方式工作

declare function boo1<T extends string>(arr: T1<T>[]): void

boo1([
{ path: 'some_path', handler: handlerWithoutError },
{ path: 'other_path', handler: handlerWithError },
])

我需要“处理程序”函数的参数来分别匹配数组中每一项的“路径”。对于第二项,它应该是一个错误,而第一个不是。如何解决该问题并强制 TS 显示正确的提示? Playground

最佳答案

我建议您使用以下调用签名:

declare function boo1<T extends string[]>(
arr: [...{ [I in keyof T]: T1<T[I]> }]
): void

函数是generic在类型参数中 T对应于tuple foo1() 中的类型参数.然后 arr属于 mapped tuple type {[I in keyof T]: T1<T[I]> }转换 T变成每个元素都用 T1<> 包裹的版本.好吧,主要是那种类型;它包裹在 variadic tuple type[... + ]给编译器一个提示,你想推断出 arr的类型为元组,而不是任意长度的无序数组。

让我们看看调用它时会发生什么:

declare const x: T1<"a">;
declare const y: T1<"b">;
declare const z: T1<"c">;
boo1([x, y, z]); // okay
// function boo1<["a", "b", "c"]>(arr: [T1<"a">, T1<"b">, T1<"c">]): void

参数arr[x, y, z] .这被推断为元组类型 [T1<"a">, T1<"b">, T1<"c">] (因为调用签名中的可变元组 [... + ];与不使用 tha 时发生的情况相比)。然后编译器能够推断出 T来自映射类型 { [I in keyof T]: T1<T[I]> }成为["a", "b", "c"] .鉴于该推断,调用类型检查成功。

让我们看看调用错误时会发生什么:

boo1([
{ path: 'some_path', handler: handlerWithoutError }, // okay
{ path: 'other_path', handler: handlerWithError }, // error!
// -----------------> ~~~~~~~
// Type '"other_path"' is not assignable to type '"wrong_path"'.
])
// function boo1<["some_path", "other_path"]>(
// arr: [T1<"some_path">, T1<"other_path">]): void

此处编译器推断出 T成为["some_path", "other_path"]来自 path特性。这意味着 arr应该是 [T1<"some_path">, T1<"other_path">] 类型. arr的第一个元素类型为 T1<"some_path"> , 但第二个元素不是 T1<"other_path"> 类型, 所以你得到了想要的错误。

Playground link to code

关于typescript - 如何获取数组中的常见类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74755615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com