typescript:用于表示任何基本类型的值类型

时间:2014-03-18 21:12:35

标签: javascript typescript

定义可以采用任何stringnumberboolean原始值的属性的最佳方法是什么。我需要一个属性来接受任何这些原始类型作为来自html输入字段(可以是text / int / bool)的值。我正在寻找any错过类型安全(具体来说,它不应该是对象,函数类型)。

2 个答案:

答案 0 :(得分:2)

从Typescript 1.4开始,你可以创建一个这样的联合类型:

type Primitive = string | boolean | number;

并像这样使用它:

function acceptPrimitive(prim: Primitive) {
  // prim is of a primitive type
}

答案 1 :(得分:1)

您可以定义接受这些功能的功能,而不是属性。

要使该功能专门接受stringnumberboolean,您将使用重载。实现签名(类型为any)实际上不可调用,因此不允许其他类型。

class Example {
    storeMyThing(input: number): void;
    storeMyThing(input: boolean): void;
    storeMyThing(input: string): void;
    storeMyThing(input: any) {
        console.log(typeof input);
        console.log(input);
    }
}

var example = new Example();

// Yes
example.storeMyThing(1);
example.storeMyThing(true);
example.storeMyThing('String');

// No
example.storeMyThing(['Arr', 'Arr']);
example.storeMyThing({ prop: 'val'});
相关问题