Ninja
Ninja

Reputation: 2098

Typescript casting

How can I make my typescript compiler happy without changing the interface and typeof argument I'm receiving in function test.

Error in function test:-

"Property 'method2' does not exist on type 'xyz'. Did you mean 'method1'?"

interface xyz { 
    method1(): string;
}

class abc implements xyz { 
    method1() { 
        return "abc";
    }
    method2() { 
        return "new method";
    }
}

function test(arg: xyz) {
    alert(arg.method2());
}

Link

Upvotes: 0

Views: 121

Answers (3)

Ninja
Ninja

Reputation: 2098

After going through documents, got to know about Type assertions, which helped me to compile that small piece of code successfully.

function test(arg: xyz) {
   var arg2 = <abc>arg; 
   alert(arg2.method2());
}

https://www.typescriptlang.org/docs/handbook/basic-types.html

Upvotes: 1

Duncan
Duncan

Reputation: 95742

You can use a type guard to change the type that is seen at the compiler when you want to access the other fields:

function isAbc(arg: xyz | abc): arg is abc {
    return (<abc>arg).method2 !== undefined;
}

function test(arg: xyz) {
    if (isAbc(arg)) {
        // here the type of `arg` is `abc`
        alert(arg.method2());
    }
}

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68685

Actually you can't.

Why ?

To make your code to pass compiler you need either add the method2 into the interface xyz or change the type parameter to accept the type abc. But you don't want neither.

Upvotes: 2

Related Questions