/ Gists / Utility type: Pick
On gists

Utility type: Pick

Typescript

index.ts Raw #

/*
Pick:

Pick<T, K> je utility typ v TypeScriptu, který vytváří nový typ výběrem určitých vlastností K z typu T.
Používá se pro vytvoření podmnožiny existujícího typu.
*/

// 1
interface User {
    id: number;
    name: string;
    email: string;
    phone: number;
}

type UserInfo = Pick<User, 'id' | 'name'>;
type UserBasicInfo = Pick<User, 'name' | 'email'>;

const user: UserInfo = {
    id: 1,
    name: 'abc',
};

const userDetails: UserBasicInfo = {
    name: 'abc',
    email: 'abc@gmail.com',
};

interface TestedPerson {
    name: string;
    age: number;
    address: string;
    email: string;
    phone: string;
}

// 2 Kombinace Pick s jinými utility typy
type OptionalPersonBasicInfo = Partial<Pick<TestedPerson, 'name' | 'age'>>;

const partialBasicInfo: OptionalPersonBasicInfo = {
    name: 'Bob',
    // age může být vynecháno
};

// 3 Použití Pick s vnořenými objekty
interface ComplexPerson {
    name: string;
    age: number;
    address: {
        street: string;
        city: string;
        country: string;
    };
}

type PersonNameAndCity = Pick<ComplexPerson, 'name'> & Pick<ComplexPerson['address'], 'city'>;

const nameAndCity: PersonNameAndCity = {
    name: 'Charlie',
    city: 'New York',
};