const data = { a: 3, hello: 'world'} function get(o: object, name: string) { return o[name]} 我们刚开始可能会这么写,不过它有很多缺点 无法确认返回类型:这将损失 ts 最大的类型校验功能 无法对 key 做约束:可能会犯拼写错误的问题 这时可以使用 keyof 来加强 get 函数的类型功能,有兴趣的同学...
无法对 key 进行约束,可能会犯拼写的错误 这时我们可以使用 keyof 来增强 getValue 函数的类型功能。 使用keyof 后我们可以看到,可以完整的提示可以输入的值,当拼写错误时也会有清晰的提示。 functiongetValue<TextendsObject, Kextendskeyof T>(o: T,key: K): T[K] {returno[key]; }constobj1 = {name:...
function isValidKey( key: string | number | symbol, object: object ): key is keyof typeof object { return key in object; } 1. 2. 3. 4. 5. 6. 这个isValidKey接收两个参数,第一个类型可能是string | number | symbol,第二个是一个object,它的返回值是一个boolean类型,看的出,true就是key...
无法对 key 进行约束,可能会犯拼写的错误 这时我们可以使用 keyof 来增强 getValue 函数的类型功能。 使用keyof 后我们可以看到,可以完整的提示可以输入的值,当拼写错误时也会有清晰的提示。 function getValue<T extends Object, K extends keyof T>(o: T, key: K): T[K] { return o[key]; } const o...
function prop<T extends object, K extends keyof T>(obj: T, key: K) { return obj[key]; } 在以上代码中,我们使用了 TypeScript 的泛型和泛型约束。首先定义了 T 类型并使用 extends 关键字约束该类型必须是 object 类型的子类型,然后使用 keyof 操作符获取 T 类型的所有键,其返回类型是联合类型,最后...
keyof is a keyword in TypeScript which is used to extract the key type from an object type.keyof with explicit keysWhen used on an object type with explicit keys, keyof creates a union type with those keys.ExampleGet your own TypeScript Server interface Person { name: string; age: number...
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}' 元素隐式地拥有 any 类型,因为 string 类型不能被用于索引 {} 类型。要解决这个问题,你可以使用以下非常暴力的方案: functionprop(obj:object, key:string){return(objasany)[key]; ...
// typeof foo === Foo,这里只所以用 typeof foo,因为这样方便,对于不想写interface的直接量对象很容易获取它的类型 //keyof typeof foo这里只获取Foo的类型的key值,注意这个keyof后面一定是 typescript的类型 type FooType= keyoftypeoffoo; vargetPropertyValue = Object.keys(foo).map(item => foo[item...
以上代码中, 类型P类型为"x" | "y" 联合类型 如果这个类型有一个 string 或者 number 类型的索引签名,keyof 则会直接返回这些类型:
const NumericObject = { [1]: "冴羽一号", [2]: "冴羽二号", [3]: "冴羽三号"};type result = keyof typeof NumericObject// typeof NumbericObject 的结果为:// {// 1: string;// 2: string;// 3: string;// }// 所以最终的结果为:// type result = 1 | 2 | 3 ...