basarat / basarat/typescript-book
Method overloading and instanceof with interfaces
- Dominant language
- TypeScript
- Stars
- 21.6k
- Forks
- 2.6k
- PR merge metrics
- No merged PRs in 30d
Description
Hi,
the book deals only with overloaded function with primitive type parameters. However I wonder what is the best practice when the parameters have interface types.
```typescript
interface Interface1{}
interface Interface2{}
class MyClass{
public method(p:Interface1){}
public method(p:Interface2){}
}
```
This gives the compiler error:
Error:(6, 12) TS2393: Duplicate function implementation.
The approach
```typescript
class MyClass2{
public method(...args:Array){
if(args[0] instanceof Interface1){
method_Interface1(args[0]);
}
else if(args[0] instanceof Interface2){
method_Interface2(args[0]);
}
}
private method_Interface1(p:Interface1){}
private method_Interface2(p:Interface2){}
}
```
cannot work, because the interfaces are not available in the transpiled JavaScript, so that instanceof cannot be used. The compiler gives the errors
Error:(12, 31) TS2304: Cannot find name 'Interface1'.
Error:(12, 31) TS2304: Cannot find name 'Interface2'.
Contributor guide
Research direction
Review the book’s material on method overloading and the interface example in this issue first. Determine whether the documentation should explain the compiler limitation and an appropriate way to handle interface-typed arguments; done means the book gives a clear recommendation that addresses the reported errors. No file or test is named in the issue.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100