Jak połączyć dwa typy w jeden?

0
type GetAllValues<P1, P2> = {
    [P in keyof P1 | keyof P2] : P1[P] | P2[P]
}
  
type F = GetAllValues<{ a: boolean; b: string; z: string }, { a: string; c: string; z: number }>;

Chciałem uzyskać wartość z 1 lub drugiego zbioru, i dostaje wiadomość

Type 'P' cannot be used to index type 'P1'.ts(2536)
0

Tzn. jakie właściwości mają być dokładnie dozwolone, a jakie nie?

Bo możesz użyć unii a | b albo Partial<a> & Partial<b> wtedy:

type a = {
    foo: number,
    bar: number,
};

type b = {
    name: string,
    city: string,
};

let union: a | b = {foo: 1, bar: 2};
union = {name: 'Alice', city: 'Warsaw'};
// union = {name: 'Bob'}; // błąd
// union = {name: 'Bob', foo: 2}; // błąd

let partial: Partial<a> & Partial<b> = {name:'John', city: 'Warsaw', foo: 3};
partial = {name: 'Alice'};

https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html
https://www.typescriptlang.org/docs/handbook/utility-types.html#partialtype

0
type a = {
    foo: number,
    name: boolean
};

type b = {
    name: string,
    city: string,
};

Wynik:

{
 foo: number;
 name: boolean | string;
 city: string;
}
0

a gdzie odpowiedż xd?

0

dobra samemu udało mi się napisać ten typ

type GetSameValues<P1, P2> = {
    [P in keyof P1 | keyof P2] : P extends keyof P1 ? (P extends keyof P2 ? P1[P] | P2[P] : P1[P]) : P extends keyof P2 ? P2[P] : never
}
 
2
phanc napisał(a):

dobra samemu udało mi się napisać ten typ

type GetSameValues<P1, P2> = {
    [P in keyof P1 | keyof P2] : P extends keyof P1 ? (P extends keyof P2 ? P1[P] | P2[P] : P1[P]) : P extends keyof P2 ? P2[P] : never
}
 

Można trochę krócej:

type GetSameValues<P1, P2> = {
    [P in keyof P1 | keyof P2] : (P extends keyof P1 ? P1[P] : never) | (P extends keyof P2 ? P2[P] : never)
}

ale bardzo dziwne wymaganie. Po co ci to

0

a tak sobie w ramach ćwiczeń wymyśliłem

1 użytkowników online, w tym zalogowanych: 0, gości: 1