但切记不要用于 interface,否则会出错 infer 先看官方解释: Within the extends clause of a conditional type, it is now possible to have infer declarations that introduce a type variable to be inferred. Such inferred type variables may be referenced in the true branch of the conditional type. It ...
interface iUserInfo { name: string; age: number; } type keys = keyof iUserInfo; 1. 2. 3. 4. 5. keyof 的简单栗子 我们有这样一个需求,实现一个函数 getValue 取得对象的 value。在未接触 keyof 时,我们一般会这样写: function getValue(o: object, key: string) { return o[key]; } const ...
function prop(obj: object, key: string) { return obj[key]; } 1. 2. 3. 在上面代码中,为了避免调用 prop 函数时传入错误的参数类型,我们为 obj 和 key 参数设置了类型,分别为 {} 和 string 类型。然而,事情并没有那么简单。针对上述的代码,TypeScript 编译器会输出以下错误信息: Element implicitly ha...
interface IRead { name?: string; age?: number; interest?: string; } type T = Required<IRead > T => { name: string; age: number; interest: string; }Pick Pick 的作用是将某个类型中的子属性挑出来,变成包含这个类型部分属性的子类型。
interface Person { name: string; age: number; location: string; } type K1 = keyof Person; // "name" | "age" | "location" type K2 = keyof Person[]; // number | "length" | "push" | "concat" | ... type K3 = keyof { [x: string]: Person }; // string | number 除了接口...
interface Person { name: string; age?: number; [propName: string]: string; } let tom: Person = { name: 'Tom', age: 25, gender: 'male' }; // index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'. // index.ts(7,5...
typeof 操作符用来在类型上下文中获取变量或者属性的类型。示例代码如下: interface IPerson { name: string; age: number; } const user: IPerson = { name: "jenny", age: 18, }; type student = typeof user; // IPerson keyof keyof 操作符用来获取某种类型的所有 key 值,返回一个联合类型。示例代码...
interface Person { name: string; age: number; } // 方法一:使用类型断言 const nameType1 = typeof ({} as Person).name; // string const ageType1 = typeof ({} as Person).age; // number // 方法二:使用映射类型 type PersonTypes = { [K in keyof Person]: Person[K]; }; // 方法...
interface Person { name:string; age: number; location:string; }typeK1 = keyof Person; //"name"|"age"|"location"typeK2 = keyof Person[]; // number |"length"|"push"|"concat"| ...typeK3 = keyof { [x:string]: Person }; //string| number ...
一: 当把keyof用在一般常见的class类型和interface类型上 type Point = { 0: number; height: number }; interface Point2{name: string; age: number} type KeyOfPoint = keyof Point; // 0 | 'height' type KeyOfPoint2 = keyof Point2; // 'name' | 'age' ...