【问题标题】:TypeScript Utility Types use caseTypeScript 实用程序类型用例
【发布时间】:2023-02-03 21:17:19
【问题描述】:
type Product = {
name: string;
price: number;
}
// Utility Type A
type Keys<T> = keyof T & string;
// Utility Type A without "& string"
type Keys<T> = keyof T & string;
type KeysOfProduct = Keys<Product>
鉴于上述条件,当我们使用 Utility Type A 或不带“& string”的 Utility Type A 时有什么区别
【问题讨论】:
标签:
typescript
typescript-utility
【解决方案1】:
没有。在这种情况下,& string 会导致有效的空操作。自从钥匙Product 是字符串文字(name、price),与一般的string 类型相交只会导致表示字符串文字name 和price 的类型。
如果你想允许松散的字符串以及强类型的字符串,你会做keyof T | string。
【解决方案2】:
& string 用于消除对象的任何不是字符串的键。换句话说,它摆脱了数字和符号。
例如:
const foo = Symbol();
type Product = {
name: string;
price: number;
[3]: boolean;
[foo]: string;
}
type KeysWithoutString<T> = keyof T;
type KeysWithString<T> = keyof T & string
const example1: KeysWithoutString<Product> = 'name';
const example2: KeysWithoutString<Product> = 'price';
const example3: KeysWithoutString<Product> = 'error'; // Error (not a key)
const example4: KeysWithoutString<Product> = 3; // Allow
const example5: KeysWithoutString<Product> = foo; // Allowed
const example6: KeysWithString<Product> = 'name';
const example7: KeysWithString<Product> = 'price';
const example8: KeysWithString<Product> = 'error'; // Error (not a key)
const example9: KeysWithString<Product> = 3; // Error (a key, but not a string)
const example10: KeysWithString<Product> = foo; // Error (a key, but not a string
Playground Link