typescript:值类型来表示任何原始类型

bsr*_*bsr 7 javascript typescript

定义可以采用string,numberboolean原始值中的任何一个的属性的最佳方法是什么。我需要一个属性来接受任何这些原始类型作为来自 html 输入字段(可以是 text/int/bool)的值。有any小姐类型安全我一直在寻找(具体而言,它不应该是目标,功能型)。

Joh*_*art 12

从 Typescript 1.4 开始,您可以像这样创建联合类型:

type Primitive = string | boolean | number;
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

function acceptPrimitive(prim: Primitive) {
  // prim is of a primitive type
}
Run Code Online (Sandbox Code Playgroud)


Fen*_*ton 0

您可以定义一个接受这些的函数,而不是属性。

要使该函数专门只接受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'});
Run Code Online (Sandbox Code Playgroud)