TypeScript学习一:基础类型

101 阅读1分钟

基础类型

数字

const num: number = 123;

布尔

const bool: boolean = true;

字符串

const str: string = "abc";

数组

const list: number[] = [1, 2, 3]; // const list2: Array<number> = [1, 2, 3];

Undefined

const u: undefined = undefined;

Null

const n: null = null;

Object

const obj: object = {};

Symbol

const sym: symbol = Symbol();

元组 Tuple

let tuple1: [string, number, boolean];
tuple1 = ["a", 123, false];

枚举 enum

  • 根据上一个值如果是数字则进行递增, 变量或者计算等则必须设置初始值

Roles[0] = SUPER_ADMIN

Roles.USER = 2

enum Roles {
  SUPER_ADMIN = 0,
  ADMIN = 1,
  USER
}

Any: 任意类型

let value: any;
value = 123;
value = "abc";

Void: 没有任何类型

const voidText = (text: string): void => {
  console.log(text);
};
voidText("void");

Never: 没有任何类型

该函数只会返回异常

const errFunc = (msg: string): never => {
  throw new Error(msg);
};

as: 类型断言

该函数只会返回异常

const getLength = (target: string | number) => {
  // 参数有可能是string | number
  // 使用断言判断参数为string类型
  if ((target as string).length || (target as string).length === 0) {
    return (target as string).length;
  } else {
    // number没有length
    return target.toString().length;
  }
};