1

Since TypeScript 3.0 the new top type unknown is available as a type-safe counterpart of any.

I really love this type, as it makes the code even more robust.

My main problem with this is, that TypeScript (obviously) does not provide an instanceof-feature at runtime for interfaces. If it would (be possible), this code would work quite well:

class Test {

  doSomething(value: unknown) {
    if(value instanceof MySuperInterface) {
      return value.superFunction();
    }

    return false;
  }

} 

My question

How do I use this type in a meaningful way, without the need of checking each property of my interface?

scipper
  • 2,944
  • 3
  • 22
  • 45

1 Answers1

0

Javascipt does not check for interface type at runtime.

instanceof check on interface

But, you can use unknown type with classes as shown below:

interface MySuperInterface {
    superfunction(): string;
}

class MySuperImplementation implements MySuperInterface {
    superfunction(): string {
        return "Hello from super function";
    }
}

class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }

    testSuperFunction(value: unknown) {
        if (value instanceof MySuperImplementation) {
            return value.superfunction();
        }
        else {
            return "Error";
        }
    }
}

let greeter = new Greeter("world");

const sfunc = new MySuperImplementation();

console.log(greeter.testSuperFunction(sfunc));

Playground

BlueStaggo
  • 171
  • 1
  • 12
Srujal Kachhela
  • 209
  • 1
  • 4
  • 15