我有一个小代码,TS让我抓狂。。。
type MyCustomType<T extends Record<string, string>> = {
key: keyof T;
};
export const myFunction = <T extends Record<string, string>>(variable: MyCustomType<T>) => {
const newVar: string = variable.key;
};
Typescript一直抱怨变量.key可以是字符串|数字|符号,并且不能分配给newVar。但我将我的通用对象键入为Record<字符串,字符串>。
那么,为什么TS猜不出这是一个字符串呢?
如何在不使用作为的情况下键入这些
非常感谢!
编译器不会将keyof T
推断为string
,因为它不必是string
。您的约束仅声明每个string
键必须具有一个string
值。但是T
也可能具有number
或symbol
密钥。
myFunction<Record<0, string>>({ key: 0 })
// no error, the constraint is fulfilled
因此,我们应该明确禁止number
和symbol
密钥。
type MyCustomType<
T extends Record<string, string>
& Record<number | symbol, never>
> = {
key: keyof T & string;
};
export const myFunction = <
T extends Record<string, string>
& Record<number | symbol, never>
>(variable: MyCustomType<T>) => {
const newVar: string = variable.key;
console.log(newVar)
};
这仍然不能消除错误。TypeScript无法推断keyof T
是string
。毕竟,它仍然可以具有never
类型的number
属性(这实际上是不可能的,但您仍然可以显式传递包含never
值的类型(。但我们现在可以"安全地">与CCD_ 16和CCD_。
游乐场