2016-11-16 105 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;