在 typescript 中有什么方法可以为变量分配通用对象类型。 这就是我所说的“通用对象类型”
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
即它应该只允许将 javascript 对象分配给变量,不允许其他类型的数据(数字、字符串、 bool 值)
最佳答案
当然了:
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
关于typescript - typescript 中的通用对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40641370/