欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

typescript——高级类型

程序员文章站 2022-07-12 15:48:35
...

Partial

interface Itest {
  webName: string;
  age: number;
  address: string;
}
type ant = Partial<Itest>;
/* type ant = {
  webName?: string;
  age?: number;
  address?: string;
} */

Required

interface Itest {
  webName: string;
  age: number;
  address: string;
}
type ant = Required<Itest>;
/* type ant = {
  webName: string;
  age: number;
  address: string;
} */

Readonly

interface Itest {
  webName: string;
  age?: number;
  address: string;
}
type ant = Readonly<Itest>;
/* type ant = {
  readonly webName: string;
  readonly age?: number;
  readonly address: string;
} */

Pick

interface Itest {
  webName: string;
  age?: number;
  address: string;
}
type ant = Pick<Itest, 'age' | 'address'>;
/* type ant = {
  age?: number;
  address: string;
} */

Record

interface Itest {
  webName: string;
  age?: number;
  address: string;
}
type ant = Record<'age' | 'address', number>;
/* type ant = {
  age: number;
  address: number;
} */

keyof

keyof 是索引类型查询操作符。
假设T是一个类型,那么keyof T产生的类型是T的属性名称字符串字面量类型构成的联合类型。
特别说明: T是数据类型,并非数据本身。
代码实例如下:

interface Itest {
  webName: string;
  age: number;
  address: string;
}
type ant = keyof Itest; // type ant = "webName" | "age" | "address"

ValueOf

同 keyof,是值类型的查询操作符

interface Itest {
  webName: string;
  age: number;
  address: string;
}
type ant = ValueOf<Itest>; // type ant = string | number

条件类型

type T00 = Exclude<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "b" | "d"
type T01 = Extract<"a" | "b" | "c" | "d", "a" | "c" | "f">;  // "a" | "c"

type T02 = Exclude<string | number | (() => void), Function>;  // string | number
type T03 = Extract<string | number | (() => void), Function>;  // () => void

type T04 = NonNullable<string | number | undefined>;  // string | number
type T05 = NonNullable<(() => string) | string[] | null | undefined>;  // (() => string) | string[]

function f1(s: string) {
    return { a: 1, b: s };
}

class C {
    x = 0;
    y = 0;
}

type T10 = ReturnType<() => string>;  // string
type T11 = ReturnType<(s: string) => void>;  // void
type T12 = ReturnType<(<T>() => T)>;  // {}
type T13 = ReturnType<(<T extends U, U extends number[]>() => T)>;  // number[]
type T14 = ReturnType<typeof f1>;  // { a: number, b: string }
type T15 = ReturnType<any>;  // any
type T16 = ReturnType<never>;  // any
type T17 = ReturnType<string>;  // Error
type T18 = ReturnType<Function>;  // Error

type T20 = InstanceType<typeof C>;  // C
type T21 = InstanceType<any>;  // any
type T22 = InstanceType<never>;  // any
type T23 = InstanceType<string>;  // Error
type T24 = InstanceType<Function>;  // Error
相关标签: typescript