简体   繁体   中英

Way to define a type in typescript like [one of union of interfaces] & {//atrributes}

// The way types defined:

interface SudoA {
    foo: string;
}

interface SudoB {
    bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
    super: boolean;
}

const baz: SuperSudo = {

} 
// typescript (3.1.6) says i have to define both `bar` and `foo` for the object

What I expect is that to put super attribute and other attributes (coming from Sudo type) should be optional. The question; is this a wrong expectation? Regardless if yes or no how is this achieved?

Edit
Corrected the type of baz , my mistake :/.
What I am expecting is for SuperSudo defining only super attribute should be enough and other attributes coming from union of interfaces should be optional.

I can define a new type like
type SuperSudo<T> = T & {} but this ends up using SuperSudo<T> which I find quite verbose.

Edit2
Changed the title

Have you considered using a type discriminator?

Without one, then specifying either foo , bar or both foo and bar will always satisfy the union type.

With one might look like:

interface SudoA {
  _type: "a";
  foo: string;
}

interface SudoB {
  _type: "b";
  bar: string;
}

type Sudo = SudoA | SudoB;

type SuperSudo = Sudo & {
  super: boolean;
}

const baz1_valid: SuperSudo = {
  _type: "a",
  super: true,
  foo: "bar",
}

const baz2_valid: SuperSudo = {
  _type: "b",
  super: true,
  bar: "foo",
}

The field name does not have to be _type , it simply must be the same field name with different type values on each variant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM