首页 > 解决方案 > 为什么添加 `& string` 会修复/提高 `keyof` 的智能感知?

问题描述

如果我keyof在 TypeScript 中使用直接运算符,则当我将鼠标悬停在该类型上时智能感知将仅为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"

为什么是这样?

标签: typescriptintellisense

解决方案


键可以是字符串、数字或符号。

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,你基本上只是选择字符串键。

为了获得更好的智能感知,您可以这样做:

type showKeys<T extends keyof any> = T extends any ? T : never;

type keys = showKeys<keyof Foo>;
//type keys  = "a" | 2 | typeof sym1

推荐阅读