While working on a new project recently, I saw some new syntax here. All of the following code has been desensitized

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

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

Omit

  • Omit<K,T>A type allows us to remove certain attributes from another object type and create a new object type:
  • KIs the object type name,T: is to exclude attribute names in type K

Omit anything and Omit anything. Omit anything and Omit anything

type NewUserProps = Omit<UserDetail,'hobby'>
===
type NewUserProps = {
    favorite: string;
    readonly sex: bool;
}
Copy the code

readonly

  • bereadonlyAttributes of a tag can only be assigned at declaration time or in the constructor of a class.
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.Copy the code
  • Extension -1: TypeScript hasReadonlyArray<T>Type, which is associated withArray<T>Similar, except all the variable methods have been removed
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>'.Copy the code
  • Extension -2: Use a uppercase beginningReadonlyCan also be used directly for the entire class, eg
interface Person{ 
    name: string; 
    agent: number;
} 
type Person2 = Readonly<Person>;
Copy the code

extents

  • Extents are inherited
interface A { a: string; b: string; c: bool; } interface B extends A { e: string; f: string; } is equivalent to interface B {a: string; b: string; c: bool; e: string; f: string; }Copy the code
  • Extension – 1:PartialGenerally used to inherit partial attributes, eg
Interface Person{name: string; agent: number; } type PersonNew = Partial<Person>; Let person: PersonNew = {name: 'new name' // extends extends Partial<A> {e: string; f: string; }Copy the code