skip to Main Content

I have using TypeScript and have two interfaces, Interface1 or Interface 2, for example:

export interface Interface1 {
  propA: string;
  propB: string;
}

export interface Interface12 {
  propA: string;
  propC: string;
}

And the method that returns objects implementing one of the possible interfaces and looks something like this:

doSomething: (state): Interface1 | Interface2 | null => {
      if (state === 1) {
        return ObjectImplementingInterface1;
      }
      if (state === 2) {
        return ObjectImplementingInterface2;
      }
      return null;
    }

Afterwards, I want to use the result of that method and use a property only existing in Interface2, for example:

const varExample = this.doSomething(this.s);
      if (varExample) {
        if ('type' in varExample && varExample.type === 'Interface1') {
          this.importantResult = varExample.propA;
        }

        if ('type' in varExample && varExample.type === 'Interface2') {
          this.importantResult = varExample.propC;
        }
      } else {
        this.importantResult = 'someValue';
      }

The compiler does not let me use the propC and throws the following error:

Property 'propC' does not exist on type '(Interface1 | Interface2) & Record<"type", unknown>'.
Property 'propC' does not exist on type 'Interface1 & Record<"type", unknown>'.

How could I force TypeScript to know that this objects if definitely an object implementing Interface2?

2

Answers


  1. Typescript is unaware what type varExample has – you can inform TypeScript that it implements Interface2 by using the as keyword to assert the object’s type:

    this.importantResult = (varExample as Interface2).propC;
    
    Login or Signup to reply.
  2. You can force TypeScript to use a particular interface or type by using what’s called type assertion or type casting.
    The way we usually do so is by using the as keyword.

    this.importantResult = (varExample as Interface2).propC;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search