0

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

Suren Srapyan
68.9k14 gold badges128 silver badges119 bronze badges
asked Sep 25, 2017 at 10:07
4
  • Can you explain what the compiler is not happy about? Commented Sep 25, 2017 at 10:09
  • only option is adding method2 as a part of interface Commented Sep 25, 2017 at 10:10
  • What is your problem? What's the compiler error? What are you trying to achieve? Commented Sep 25, 2017 at 10:17
  • If you open the link I have shared you'll get to know. Copiler is throwing this error:- "Property 'method2' does not exist on type 'xyz'. Did you mean 'method1'?" Commented Sep 25, 2017 at 11:03

3 Answers 3

2

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.

answered Sep 25, 2017 at 10:09
Sign up to request clarification or add additional context in comments.

Comments

2

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());
 }
}
answered Sep 25, 2017 at 10:56

Comments

1

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

answered Sep 25, 2017 at 12:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.