是否存在一种基本上充当非原始类型的类型

时间:2018-03-15 13:11:01

标签: typescript

有没有办法设置一个类似于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

1 个答案:

答案 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