打字稿中的通用对象类型
问题描述:
在打字稿中有什么方法可以为变量分配一个通用对象类型.这就是我所说的通用对象类型"
In typescript is there any way to assign a variable a generic object type. Here's what I mean by 'generic Object type'
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
即它应该只允许将 javascript 对象分配给变量,而不允许将其他类型的数据(数字、字符串、布尔值)
i.e. It should only allow javascript objects to be assigned to the variable and no other type of data(number, string, boolean)
答
当然:
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
(操场上的代码)