Skip to content

类型

Array

Indexed Access Types

索引类型

type Arr = [1, "a", "b", 2];
type V = Arr[number]; // 获取数组的所有值的类型,1 | "a" | "b" | 2

操作符

in

  1. for…in 语句外
  2. 类型断言
interface A {
title: string;
description: string;
}
interface B {
id: string;
name: string;
}
function todo(data: A | B){
if('id' in data)
// B 类型
}else{
// A 类型
}
}

标识符

readonl

只读

overide

表示子类对父类方法的重载,但也是仅仅是一个重载标识,父级如果不存在该属性和方法则报错

class Child {
override name: string;
}

私有变量

private

class Parent {
private name = "Parent"; // 无法在ts中使用,但实际上还是可以访问的
}

private 只是在 typescript 存在私有变量,但是无论是在 js 中还是 console.log 都是可以显示出该私有变量

class Parent {
#name = "Parent"; // 无法被外部访问
}

常用实践

interface 和 type 异同

  1. 都可以声明类型,包含对象类型
  2. 都可以进行扩展,尽管扩展的方式不同
  3. 都支持泛型

  1. 语义:interface 为接口;type 为类型别名
  2. 类实现:interface 可以被类实现;type 不行
  3. 继承:interface 可以继承其他 interface,也可以继承 type;但 type 无法继承,但可以使用&、|对 type 进行扩展
  4. 声明合并:interface 声明可以合并;type 同声明会报错
  5. type 运算:type 可以进行一些列的 type 运算

定义 Node Array

定义一个数组,数组的 item 可能是一个 Node,也可以是一个 Node Array

type N<T> = T | Array<T>;
type NodeArray<T> = Array<N<T>>;
const strs: NodeArray<string> = ["a", "b", ["c"], ["d", "e", ["f"]]];

声明合并

Interface 合并

interface A {
name: string;
}
interface A {
age: number;
}
// 会合并为
interface A {
name: string;
age: number;
}

namespace 合并

namespace A {
export class B {}
}
namespace A {
export class C {}
}
// 合并为
namespace A {
export class B {}
export class C {}
}

namespace 还可以和其他类型合并,例如 class、function、enum

class A {}
namespace A {
export const id = 2; // 起始就相当于给A对象,添加了个属性
}
// 函数也是一样的
function B() {}
namespace B {
export const id = 3;
}

Enum 合并

enum A {
NAME = 1,
}
enum A {
AGE = 2,
}
// 合并为
enum A {
NAME = 1,
AGE = 2,
}

扩展

code.ts
// 使用 declare 进行扩展,不仅是扩展 interface,namespace,enum,也可以扩展 class
export class T {}
export interface G {}
export namespace K {
export interface J {}
}
export enum O {
AGE = 1,
}
// main.ts
import { T, K, G, O } from './code';
// 对本地模块进行扩展
declare module './code' {
interface T {
age: number;
}
interface G {
age: number;
}
namespace K {
interface J {
age: number;
}
}
enum O {
NAME = 2,
}
}
// 对 node_modules 模块进行扩展
declare module express {
export interface Request {
...
}
}
const t: K.J = { age: O.NAME };
// 全局扩展
export {}; // 让ts识别该文件为模块,而不是脚本
declare global {
interface Array<T> {}
}

体操

Union To Object

type UnionToObject<T extends unknown> = {
[Key in T as Key extends string | number ? Key : never]: unknown;
};