Otto
Otto

Reputation: 2066

TypeScript: How to conditionally make properties required in a type, based on another object's type?

Assuming this situation:

interface A {
  a: string;
  b?: string;
  c?: string;
}

const myobj = {
  a: "test",
  b: "test2"
}

I'm trying to use generics to dynamically contruct a type like below, containing only those properties from A that are not defined on myobj:

interface AA {
  c: string;
}

How can this be done? I've attempted various strategies, e.g. using Exclude<>, Omit<> and "-?" but gotten nowhere so far.

Upvotes: 1

Views: 432

Answers (2)

Please take look on next example:

interface A {
  a: string;
  b?: string;
  c?: string;
}

const myobj = {
  a: "test",
  b: "test2"
}

type MyObj = typeof myobj;

type Intersection<T,I> = keyof A & keyof MyObj;

type Helper<T,U>={
    [P in Exclude<keyof T,U>]: T[P]
}

type Result = Helper<A,Intersection<A,MyObj>> // same as AA interface

Upvotes: 1

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

Try

interface A {
  a: string;
  b?: string;
  c?: string;
}

const myobj = {
  a: "test",
  b: "test2"
}

type B = Omit<A, keyof typeof myobj>;

const b: B = {
    a: 'a', // fails as required
    c: 'c'
};

Upvotes: 2

Related Questions