typescript - 为什么添加 `& 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"
为什么是这样?
解决方案
键可以是字符串、数字或符号。
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
推荐阅读
- javascript - 使用 PyCryptodome 进行 AES 解密不会产生预期的结果
- javascript - 如何访问和删除/删除嵌套 Javascript 对象中的属性?
- python - 使用负整数时,numpy bincount 的替代方法是什么?
- typescript - 打字稿:从对象中删除键
- reactjs - ReactJS 通过从服务器接收 json 创建组件
- php - 在 Laravel 中将刮板逻辑放在哪里?
- javascript - 仅在 API 查询成功后才提交表单以填充字段
- shell - 将列与行匹配
- r - 如何在 RStudio 中为 ggplot2 安装 Courier 字体
- c++ - 运行基于 SDL Cpp 的应用程序的问题