0
type B = {
 c: string
}
    
type T = {
  a: string
  b: B
}

I want to make T2 that will look like

type T2 = {
  a: string
  ['b' or 'prefixB']: B
}

Basically I want to have T with a and b or prefixB property - do you know how to do it in the eases way? Something like one of two

  • You can check the second answer of this question https://stackoverflow.com/questions/37688318/typescript-interface-possible-to-make-one-or-the-other-properties-required – Poyraz Yilmaz Jun 11 '21 at 08:10
  • 1
    Does this answer your question? [TypeScript a | b allows combination of both](https://stackoverflow.com/questions/46370222/typescript-a-b-allows-combination-of-both) – Oleg Valter is with Ukraine Jun 11 '21 at 13:52

2 Answers2

0
type Aa = {a: string}
type T2 =  Aa & ({prefixB: string} | {b: string})

const foo: T2 = {
  a: "a",
  b: "b"
}
foo.a // a
foo.b // b
foo.prefixB // Property 'prefixB' does not exist

const foo2: T2 = {
  a: "a",
  prefixB: "prefixB"
}
foo2.a // string
foo2.prefixB // prefixB
foo2.b // Property 'b' does not exist

i think this is work


update

type Aa = {a: string}
type B = {
  c: string
}

type T2 =  Aa & ({prefixB: B} | {b: B})

const foo: T2 = {
  a: "a",
  b: {
    c: "obj"
  },
}
foo.a // a
foo.b // { c: "obj" }
foo.prefixB // Property 'prefixB' does not exist

const foo2: T2 = {
  a: "a",
  prefixB: {
    c: "obj"
  }
}
foo2.a // a
foo2.prefixB // { c: "obj" }
foo2.b // Property 'b' does not exist

const foo3: T2 = {
  a: "a",
  prefixB: {
    c: "obj"
  },
  b: {
    c: "obj"
  }
}
foo3.a // a
foo3.prefixB //  Property 'prefixB' does not exist
foo3.b // Property 'b' does not exist
yun
  • 94
  • 7
0

I believe the easiest non-generic way is to define T2 as:

type T2 = 
  | { a: string, b: B, prefixB?: never } 
  | { a: string, b?: never, prefixB: B }

playground link

aleksxor
  • 7,535
  • 1
  • 22
  • 27
  • good idea - it works perfect, thanks! I'm curious if we can simplify somehow :D. I'm filling that I miss some cool part of TS – user16195583 Jun 11 '21 at 09:24
  • You may implement some sort of generic helper to generate such types. But that will not be 'easier` definitely. – aleksxor Jun 11 '21 at 09:26