如果我在TypeScript中使用直接的keyof运算符,当我将鼠标放在该类型上时,智能感知将只是keyof TheType。然而,如果我添加& string,它将提供更有用的字符串联合列表。
type Foo = {
a: string;
b: number;
c: () => void;
};
type A = "a" | "b" | "c";
//type A = "a" | "b" | "c"
type B = keyof Foo;
//type B = keyof Foo
type C = keyof Foo & string;
//type C = "a" | "b" | "c"为什么会这样呢?
发布于 2021-10-12 23:25:41
键可以是字符串、数字或符号。
const sym1 = Symbol();
type Foo = {
a: number,
2: string,
[sym1]: boolean,
}
type keys = keyof Foo;
type isString = keys extends string ? true : false;
//type isString = false
type isKey = keys extends string | number | symbol ? true : false;
//type isKey = true当您执行keyof Foo & string时,您基本上只选择了字符串键。
要获得更好的intellisense,您可以这样做:
type showKeys<T extends keyof any> = T extends any ? T : never;
type keys = showKeys<keyof Foo>;
//type keys = "a" | 2 | typeof sym1https://stackoverflow.com/questions/69547866
复制相似问题