成都汇智知了堂IT培训机构
IT培训课程升级
IT培训机构知了堂联系方式

TypeScript文字类型

文字是集合类型的更具体的子类型。这意味着是"Hello World"a string,但astring不在"Hello World"类型系统内部。


今天,TypeScript提供了三组文字类型:字符串,数字和布尔值;通过使用文字类型,您可以允许一个字符串,数字或布尔值必须具有的精确值。


字面缩小

当您通过var或声明变量时let,您是在告诉编译器该变量可能会更改其内容。相反,const用于声明变量将通知TypeScript该对象永远不会改变。


// We're making a guarantee that this variable

// helloWorld will never change, by using const.


// So, TypeScript sets the type to be "Hello World", not string

const helloWorld = "Hello World";


// On the other hand, a let can change, and so the compiler declares it a string

let hiWorld = "Hi World";尝试

从无限数量的潜在情况(有无限数量的可能的字符串值)到较小,有限数量的潜在情况(在helloWorld案例中为1)的过程称为变窄。


字符串文字类型

在实践中,字符串文字类型与联合类型,类型保护和类型别名很好地结合在一起。您可以将这些功能一起使用,以获得类似于枚举的字符串行为。


type Easing = "ease-in" | "ease-out" | "ease-in-out";


class UIElement {

  animate(dx: number, dy: number, easing: Easing) {

    if (easing === "ease-in") {

      // ...

    } else if (easing === "ease-out") {

    } else if (easing === "ease-in-out") {

    } else {

      // It's possible that someone could reach this

      // by ignoring your types though.

    }

  }

}


let button = new UIElement();

button.animate(0, 0, "ease-in");

button.animate(0, 0, "uneasy");

Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.

尝试

您可以传递三个允许的字符串中的任何一个,但是任何其他字符串都会给出错误


Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'

可以使用相同的方式使用字符串文字类型来区分重载:


function createElement(tagName: "img"): HTMLImageElement;

function createElement(tagName: "input"): HTMLInputElement;

// ... more overloads ...

function createElement(tagName: string): Element {

  // ... code goes here ...

}

数值文字类型

TypeScript还具有数字文字类型,其作用与上面的字符串文字相同。


function rollDice(): 1 | 2 | 3 | 4 | 5 | 6 {

  return (Math.floor(Math.random() * 6) + 1) as 1 | 2 | 3 | 4 | 5 | 6;

}


const result = rollDice();尝试

使用它们的常见情况是用于描述配置值:


interface MapConfig {

  lng: number;

  lat: number;

  tileSize: 8 | 16 | 32;

}


setupMap({ lng: -73.935242, lat: 40.73061, tileSize: 16 });尝试

布尔文字类型

TypeScript也具有布尔文字类型。您可以使用它们来约束属性相互关联的对象值。


interface ValidationSuccess {

  isValid: true;

  reason: null;

}


interface ValidationFailure {

  isValid: false;

  reason: string;

}


type ValidationResult = ValidationSuccess | ValidationFailure;


实战教学·项目驱动

177 1362 3990
预约免费试学
点击咨询
预约试学