Typescript 语法进阶

762 阅读2分钟

最近在做新的项目,看到一些新的语法在此记录下, 以下所有代码都做了脱敏处理

export interface UserDetail {
    hobby: string;
    favorite: string;
    readonly sex: bool;
}

export interface User extends Omit<UserDetail, 'hobby'> {
    name: string;
    id: string;
}

Omit

  • Omit<K,T>类型让我们可以从另一个对象类型中剔除某些属性,并创建一个新的对象类型:
  • K:是对象类型名称,T:是剔除K类型中的属性名称 所以上文中的 Omit<UserDetail, 'hobby'>就是
type NewUserProps = Omit<UserDetail,'hobby'>
===
type NewUserProps = {
    favorite: string;
    readonly sex: bool;
}

readonly

  • 被 readonly 标记的属性只能在声明时或类的构造函数中赋值。
interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
⨯ Unable to compile TypeScript:
src/interface_3.ts(7,4): error TS2540: Cannot assign to 'x' because it is a constant or a read-only property.
  • 扩展-1 :TypeScript具有ReadonlyArray<T>类型,它与Array<T>相似,只是把所有可变方法去掉了
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!

⨯ Unable to compile TypeScript:
src/interface_3.ts(11,1): error TS2542: Index signature in type 'ReadonlyArray<number>' only permits reading.
src/interface_3.ts(12,4): error TS2339: Property 'push' does not exist on type 'ReadonlyArray<number>'.
src/interface_3.ts(13,4): error TS2540: Cannot assign to 'length' because it is a constant or a read-only property.
src/interface_3.ts(14,1): error TS2322: Type 'ReadonlyArray<number>' is not assignable to type 'number[]'.
  Property 'push' is missing in type 'ReadonlyArray<number>'.
  • 扩展-2 :使用大写的开头Readonly的还可以直接用于整个类, eg
interface Person{ 
    name: string; 
    agent: number;
} 
type Person2 = Readonly<Person>;

extents

  • extents 是继承
interface A {
    a: string;
    b: string;
    c: bool;
}

interface B extends A {
    e: string;
    f: string;
}
等价于 
interface B {
    a: string;
    b: string;
    c: bool;
    e: string;
    f: string;
}
  • 扩展-1 :Partial一般用于继承部分属性, eg
//用法1 直接使用
interface Person{
    name: string;
    agent: number;
}
type PersonNew = Partial<Person>;
let person: PersonNew = {
    name: 'new name' 
    //缺少agent属性,不完整也不会报错
}

//用法2 与extends 连用
interface B extends Partial<A> {
    e: string;
    f: string;
}