有没有办法设置一个类似于any
的类型,但是不允许分配原始值?
type Demogorgon = { friendly: boolean };
const sarah: Demogorgon = { friendly: true };
const duck = 'is in the upside down';
let anyNonPrimitive: any; // What type can replace 'any' and make the following comments true?
anyNonPrimitive = duck; // should fail assignment
anyNonPrimitive = sarah; // should allow assignment
console.log(anyNonPrimitive.friendly); // property 'friendly' should be accessible
console.log(anyNonPrimitive.unicorns); // does not cause type error, returns undefined
答案 0 :(得分:2)
@Tao,真正的用例是在JSON API的结果中添加一个相当无限制的类型,其结果可以是任何非基本类型。
您可以使用索引类型,它允许特定类型的任何键。对于松散的JSON,它可能是这样的。
interface JsonObject {
[key: string]: JsonValue
}
interface JsonArray extends Array<JsonValue> {}
type JsonValue = null | string | number | boolean | JsonArray | JsonObject;
现在,如果你想扩展一个强大的界面,你可以将它与JsonObject
相交。
let anyNonPrimitive: JsonObject & Demogorgon;
anyNonPrimitive = duck; // error
anyNonPrimitive = sarah; // works
console.log(anyNonPrimitive.friendly); // 'friendly' is boolean
console.log(anyNonPrimitive.unicorns); // 'unicorns' is JsonValue