TypeScript Optional Sub-Properties

Viewed 41

So I know that there is a way to create a type-alias to have properties such as answer I have seen from another user in this post (Typescript interface optional properties depending on other property) like below:

type Sample = {
  key1: true,
  key2?: string,
  key3: number
} | {
  key1: false,
  key2?: string,
  key3?: never
}

but how would I do it if the dependent properties are inside (as in, both key2 and key3 belong to key1, but key3 would exist only if key2 is true)? Would it be something like this:

type Sample = {
  key1: {
  key2?: true,
  key3: number
 }
} | {
  key1: {
  key2?: false,
  key3?: never
 }
}
1 Answers

An option is to just make the distinction inside like this:

type Sample = {
  key1: {
  key2?: true,
  key3: number
 } | {
  key2?: false,
  key3?: never
 }
}

Your code actually works too

Related