在打字稿中,有什么方法可以为变量分配通用对象类型。
这就是我所说的“通用对象类型”的含义
let myVariable: GenericObject = 1 // Should throw an error
= 'abc' // Should throw an error
= {} // OK
= {name: 'qwerty'} //OK
即它应该只允许将 javascript 对象分配给变量,而不允许其他类型的数据(数字、字符串、布尔值)
当然有:
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
(操场上的代码 https://www.typescriptlang.org/play/#src=type%20GenericObject%20%3D%20%7B%20%5Bkey%3A%20string%5D%3A%20any%20%7D%3B%0A%0Alet%20myVariable1%3A%20GenericObject%20%3D%201%3B%20%2F%2F%20Type%20'number'%20is%20not%20assignable%20to%20type%20'%7B%20%5Bkey%3A%20string%5D%3A%20any%3B%20%7D'%0Alet%20myVariable2%3A%20GenericObject%20%3D%20'abc'%3B%20%2F%2F%20Type%20'string'%20is%20not%20assignable%20to%20type%20'%7B%20%5Bkey%3A%20string%5D%3A%20any%3B%20%7D'%0Alet%20myVariable3%3A%20GenericObject%20%3D%20%7B%7D%20%2F%2F%20OK%0Alet%20myVariable4%3A%20GenericObject%20%3D%20%7Bname%3A%20'qwerty'%7D%20%2F%2FOK)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)