在typescript中有任何方法可以为变量分配通用对象类型.这就是'泛型对象类型'的意思
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
Run Code Online (Sandbox Code Playgroud)
即它应该只允许javascript对象分配给变量而没有其他类型的数据(数字,字符串,布尔值)
Nit*_*mer 35
当然可以:
type GenericObject = { [key: string]: any };
let myVariable1: GenericObject = 1; // Type 'number' is not assignable to type '{ [key: string]: any; }'
let myVariable2: GenericObject = 'abc'; // Type 'string' is not assignable to type '{ [key: string]: any; }'
let myVariable3: GenericObject = {} // OK
let myVariable4: GenericObject = {name: 'qwerty'} //OK
Run Code Online (Sandbox Code Playgroud)
(游乐场代码)
Jar*_*eer 35
Typescript 2.1+ 也有一个实用程序类型, Record<K, T>,你可以使用而不是自己定义
const myObj: Record<string, any>;
Run Code Online (Sandbox Code Playgroud)
当我可以给出一个有意义的名字时,我喜欢使用 top answer 中描述的样式,key但如果它不是那么明显或必要的话,这Record是一个很好的选择。
| 归档时间: |
|
| 查看次数: |
13407 次 |
| 最近记录: |