Skip to content
Published at:

Everyday Types

The primitives:

  • string: 字符串类型
  • number: 数字类型; 包括 int 和 float,都叫数字
  • boolean: 布尔类型

Arrays

ts
const arr: number[] = [1, 2, 3];
const arr: Array<number> = [1, 2, 3];
const arr = [1, 2, 3];

any

noImplicitAny 配置

any没有类型检查;开启编译器配置 noImplicitAny, 遇到隐式的 any 就会报错

Type Assertions

类型断言

ts
// as写法
const myCanvas = document.getElementById('main_canvas') as HTMLCanvasElement;
// angle-bracket syntax 写法
const myCanvas = <HTMLCanvasElement>document.getElementById('main_canvas');

// 极端场景 需要转两次(用any或unknown)
const a = expr as any as T;

Literal Types

对于string和number,可以用其具体的值当类型,约束取值,叫字面量类型。

单独当变量使用(只有一个取值),意义不大:

ts
let x: 'hello' = 'hello';
x = 'hello'; // OK
x = 'howdy'; // ...

更多是和unions类型一起使用:

  • 使用在函数参数、返回值
  • 和non-literal types一起使用
ts
// 使用在函数参数
function printText(s: string, alignment: 'left' | 'right' | 'center') {
  // ...
}

// 使用在函数返回值
function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

// 和non-literal types一起使用
interface Options {
  width: number;
}
function configure(x: Options | 'auto') {
  // ...
}

Literal Inference

  • number: 无用
ts
const obj = { counter: 0 };
if (someCondition) {
  obj.counter = 1; // Error ...
}
  • string: as强转
ts
declare function handleRequest(url: string, method: 'GET' | 'POST'): void;

const req = { url: 'https://example.com', method: 'GET' };
handleRequest(req.url, req.method); // req.method
// Error: Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.

解决方案:

  • 使用类型断言
  • 使用 as const 转成字面量类型
ts
//
// 使用类型断言
// Change 1:
const req = { url: 'https://example.com', method: 'GET' as 'GET' };
// Change 2:
handleRequest(req.url, req.method as 'GET');

// 使用 `as const` 转成字面量类型
const req = { url: 'https://example.com', method: 'GET' } as const;
handleRequest(req.url, req.method);

null and undefined

JavaScript里面有两个原始值: null 和 undefined.

strictNullChecks off

strictNullChecks on

ts
function doSomething(x: string | null) {
  if (x === null) {
    // do nothing
  } else {
    console.log('Hello, ' + x.toUpperCase());
  }
}

Non-null Assertion Operator (Postfix !)

使用!避免显示的 null或undefined检查

ts
function liveDangerously(x?: number | null) {
  // No error
  console.log(x!.toFixed());
}

Enums