2016-11-16 46 views
3

在typescript中是否有任何方式为变量分配一个通用对象类型。 这是我的“通用对象类型”类型描述中的通用对象类型

let myVariable: GenericObject = 1 // Should throw an error 
           = 'abc' // Should throw an error 
           = {} // OK 
           = {name: 'qwerty'} //OK 

的意思,即它应该只允许JavaScript对象被赋给变量并没有其他类型的数据(数字,字符串,布尔)

回答

7

没问题:

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 

code in playground

2

由于打字稿2.2,你可以使用

let myVariable: object;