search.png
关于我
menu.png
浅学TypeScript(3)——类型机制

TypeScript 支持的基础类型有这些:

Introduction
Boolean
Number
String
Array
Tuple
Enum
Any
Void
Null and Undefined
Never
Object

具体的使用可以参考Basic Types

写一个demo来测试这些类型

class Types {

    // boolean
    private aBoolean: boolean = true;
    private decimal: number = 6;

    // number
    private hex: number = 0xf00d;
    private binary: number = 0b1010;
    private octal: number = 0o744;
    private float: number = 1.223;

    // string
    private color: string = "blue";
    private clothes: string = `my clothes's color is ${this.color}`;

    // array
    private numList: number[] = [1, 2, 3];
    private numList2: Array<number> = [2, 3, 3];

    // tuple 元组
    private aTuple: [string, number] = ["xxx", 1];

    // enum
    private blue: Color = Color.BLUE;
    private green: string = Color[1];

    // any 任意类型
    private notSure: any = 4;
}

// enum
enum Color {RED, GREEN, BLUE = 3}

// void 不返回任何类型
function f(): void {

}

// null 和 undefined 可以赋给任意类型
let aBoolean: boolean = null;
let aString: string = undefined;

// never 类型,标识这个方法的永远不会正常返回值
function f1(): never {
    while (true);
}

// object object是一种非原始型的类型,即任何不是number,string,boolean,bigint,symbol,null,或undefined。
declare function create(o: object | null): void;

create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error

值得注意的几个地方

  1. ts 声明类型时,具体名称放在前面,而类型放在后面,如let aBoolean: boolean = true,这和我们常用的语言比较不一样,和go、kotlin有相似之处。
  2. ts没有细分数字类型,只有number
  3. 元组实际上还是数组,但是相比js的数组增加了类型检查、长度检查
  4. object指的是不包括基本类型的其余类型
  5. nerver用来标识一个不会正常返回的函数

类型推论

对于一个变量,当它被赋予基本类型时,它的类型就被确定了:

// 自动类型判断
let aString = "123";
aString = 123;  //Error:(3, 1) TS2322: Type '123' is not assignable to type 'string'.

联合类型

// 类型联合
let stringOrBoolean: string | boolean = true;
stringOrBoolean = "123";

类型断言

! 类型断言并不能强制转换,它只能断言成变量声明时对应的类型

// 类型断言
let str = <string>stringOrBoolean;
// 类型断言并不能强制转换,它只能断言成变量声明时对应的类型
// Error:(11, 11) TS2352: Conversion of type 'string' to type 'number' may be a mistake
// because neither type sufficiently overlaps with the other. If this was intentional,
// convert the expression to 'unknown' first.
let num = <number>stringOrBoolean;

let sb = <string|boolean>stringOrBoolean;

// 也可以使用as
let aBoolean: any = true;
let b = aBoolean as boolean;

类型别名

interface Animal {
    typ: string;
}
class Duck implements Animal {
    typ: string = "鸭子"
}
class Goose implements Animal {
    typ: string = "鹅"
}
class Fish implements Animal {
    typ: string = "鱼"
}

// 鸭子和鹅可以飞,但是鱼不行
type canFly = (Duck | Goose);

// 必须是可以飞的动物
function fly(animal: canFly): void {
    console.log(animal.typ + '飞走了');
}

let duck = new Duck();
fly(duck);

let goose = new Goose();
fly(goose);

// 不知道为什么期待的报错没有出现
let fish: Fish = new Fish();
fly(fish);

版权声明

知识共享许可协议 本文章由作者“衡于墨”创作,转载请注明出处,未经允许禁止用于商业用途

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。
发布时间:2019年12月05日 10:32:12

评论区#

还没有评论哦,期待您的评论!

关闭特效