Christo S. Christov
Christo S. Christov

Reputation: 2309

Match a type to a subtype without keeping extra properties

Let's say I have two types A, B

I would like to populate the values for all of the fields that match between A and B but any extra fields should not be included in the result.

How do I do this?

To make this clearer

let a : A = { a : 'b' , b : 'c' }
let b : B = { a : 'j' }

let c : A intersect B = { a : 'j' } (take only B's values)

Upvotes: 0

Views: 472

Answers (1)

I'm not sure what do you mean populate.

Here you have an example:

type A = {
    name: string;
    surname: string;
    age: number
}

type B = {
    name: string;
    surname: string;
    status: boolean;
}

type CommonFields = A | B;

type Test = keyof CommonFields

Union of types allows you to deal only with common properties.

UPDATE Let me know if it works for you

type A = { a: string, b: string }
type B = { a: string }

type Uncommon<T, U> = {
    [Prop in keyof (T & U)]: Prop extends keyof T ? Prop extends keyof U ? never : Prop : Prop
}[keyof (T & U)]

type PickUncommon<T, U> = Pick<T & U, Uncommon<T, U>>

// {
//     b: string;
// }
type Result = PickUncommon<A, B>

Playground

Upvotes: 1

Related Questions