1

I have 3 interfaces:

export interface Foo {a:string}
export interface Foo2 extends Foo {b:boolean}
export interface Foo3 extends Foo {c:number}

How do I make a class assignation without error?

class Goo {
  fooVar: Foo | Foo2 | Foo3;

  constructor() {
    this.fooVar.c = 0; <------ ERROR!
  }
}

All help is welcome :)

1
  • Possibly fooVar should use intersection rather than union types (Foo & Foo2 & Foo3), but it also depends on what you're doing specifically Commented Nov 28, 2018 at 21:30

1 Answer 1

1

There are several options (If fooVar is really supposed to be either one of Foo, Foo2 or Foo3).

The simplest solution is a type assertion :

  class Goo {
    fooVar: Foo | Foo2 | Foo3 = {
      a: ""
    };

    constructor() {
      (this.fooVar as Foo3).c = 0
    }
  }

If c is already in fooVar and you only want to assign it if it already exist (ie fooVar is already Foo3) you can use an in type guard:

  class Goo {
    fooVar: Foo | Foo2 | Foo3 = {
      a: "", c: -1
    };

    constructor() {
      if('c' in this.fooVar) this.fooVar.c = 0
    }
  }

If you don't mind changing the object reference you can use spread :

  class Goo {
    fooVar: Foo | Foo2 | Foo3 = {
      a: "", 
    };

    constructor() {
      this.fooVar = {...this.fooVar, c: 0 }
    }
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't be better to use intersection or extending types? type Foo extends...
@kinduser I am not really sure what he is trying to achieve ... the question asked how you can assign a property on a union type (at least in my reading) I tried to offer options for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.