Jarod
Jarod

Reputation: 199

How to define properties conditionally according to the conditional types for typescript interfaces

Suppose I have an existing typescript interface used in a codebase

interface example<condition extends true | false = false> {
  a: string;
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

Now I want to keep property a if condition is true, but replace property a with property d if condition is false, how can I do it?

Are there any easy ways like how javascript object can do with it like the following (has syntax error though)

interface example<condition extends true | false = false> {
  ...(condition extends true && {a: string});
  ...(condition extends false && {d: string});
  b: string;
  c: condition extends true ? string : number;
  // many other properties
}

Upvotes: 1

Views: 443

Answers (2)

Jarod
Jarod

Reputation: 199

Found a solution

type Example<Condition extends boolean = false> = {
    b: string;
    c: string;
    e: string;
    f: string;
    g: string;
    h: string;
    i: string;
} & (Condition extends true ? {
    a: string;
} : {
    d: string;
})

anyway possible to do like this by using interfaces?

Upvotes: 1

You can use next type:

type Example<Condition extends boolean = false> = Condition extends true ? {
    a: string;
    b: string;
    c: string;
} : {
    d: string;
    b: string;
    c: number;
}

Playground

According to TS convention, you should use CamelCase for types and interfaces.

Also, true | false is just a boolean

Upvotes: 1

Related Questions