2 Eylül 2021 Perşembe

TypeScript Derive New Types From Existing Types

Giriş
Açıklaması şöyle
It’s possible in TypeScript to derive new types from existing types using type unions, type intersections, mapped types, and conditional types
Type Intersection
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// Type Intersection
type EmployeeWithId = Employee & { id: string };
// This type will be equivalent to
// {
//    id: string;
//    name: string
//    age: number;
//    dob: Date;
// }

// Readonly uses Mapped Types
type ReadonlyEmployee = Readonly<Employee>;
// This type will be equivalent to
// {
//    readonly name: string
//    readonly age: number;
//    readonly dob: Date;
// }

// A Mapped Type with a Conditional Type allows for interesting transformations
type DateToString<T> = {
    [P in keyof T]: T[P] extends Date ? string : T[P];
};

type EmployeeJson = DateToString<Employee>
// This type will be equivalent to
// {
//    name: string
//    age: number;
//    dob: string; // Date has changed to string
// }
ReadOnly
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// Readonly uses Mapped Types
type ReadonlyEmployee = Readonly<Employee>;
// This type will be equivalent to
// {
//    readonly name: string
//    readonly age: number;
//    readonly dob: Date;
// }
MappedType
Örnek
Şöyle yaparız
interface Employee {
    name: string
    age: number;
    dob: Date;
}

// A Mapped Type with a Conditional Type allows for interesting transformations
type DateToString<T> = {
    [P in keyof T]: T[P] extends Date ? string : T[P];
};

type EmployeeJson = DateToString<Employee>
// This type will be equivalent to
// {
//    name: string
//    age: number;
//    dob: string; // Date has changed to string
// }

Hiç yorum yok:

Yorum Gönder