Typescript的一些常见生命用法

现在流行使用typescript进行申明,很多初学者只能使用一些简单的声明,当类型复杂之后就会不知所措。本文章收录一些typescript的常用声明,希望对你有帮助。

keyof

type Point = { x: number; y: number };
type P = keyof Point; // 等价于 “x” | “y”

typeof

let s = "hello";
let n: typeof s; // 等价于 let n: string;

ReturnType

type Predicate = (x: unknown) => boolean;
type K = ReturnType<Predicate>; // type K = boolean


function f() {
  return { x: 10, y: 3 };
}
type P = ReturnType<typeof f>;

//type P = {
//    x: number;
//    y: number;
//}

Partial<Type>

取一部分

type T = {
    a: string;
    b: number;
}

const x: Partial<T> = {
    a: 'hello'
}

Required<T>

必须全包括

type T = {
    a?: string;
    b?: number;
}

const x: Required<T> = {
    a: 'hello',
    b: 12
}

Record<keys, Types>

声明键和值类型

interface CatInfo {
  age: number;
  breed: string;
}
 
type CatName = "miffy" | "boris" | "mordred";
 
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

Pick<Type, Keys>

取指定键

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}
 
type TodoPreview = Pick<Todo, "title" | "completed">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

Omit<Type, Keys>

排除指定键

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
 
type TodoPreview = Omit<Todo, "description">;
 
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};
 

Exclude<UnionType, ExcludedMembers>

从联合键中排除指定键

type T0 = Exclude<"a" | "b" | "c", "a">;    
// type T0 = "b" | "c"

type T1 = Exclude<"a" | "b" | "c", "a" | "b">; 
// type T1 = "c"

type T2 = Exclude<string | number | (() => void), Function>;  
// type T2 = string | number

Extract<Type, Union>

提取指定键

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
     
// type T0 = "a"


type T1 = Extract<string | number | (() => void), Function>;
     
// type T1 = () => void

 

NonNullable<Type>

排除null和undefined

type T0 = NonNullable<string | number | undefined>; 
// type T0 = string | number

type T1 = NonNullable<string[] | null | undefined>; 
// type T1 = string[]

 

泛型

扩展类型

type X<T={}> = {
    a: string
} & T

const cat: X = {
    a: "Tom"
}

const dog: X<{age: number}> = {
    a: "Tom",
    age: 12
}

 

相关标签:
0人点赞

发表评论

当前游客模式,请登陆发言

所有评论(1)

用户头像
I have a dream

有用