Just look at this typescript code:
lib.ts
interface Human {
name: string;
age: number;
}
export default class HumanFactory {
getHuman(): Human {
return {
name: "John",
age: 22,
}
}
}
index.ts
import HumanFactory from "./lib";
export class Foo {
human: any;
constructor() {
const factory = new HumanFactory();
this.human = factory.getHuman();
}
diffWithError(age: number): number {
return age - this.human.name;
}
diffWithTypingAndAutocoplete(age: number): number {
const factory = new HumanFactory();
return age - factory.getHuman().name;
}
}
The problem in "human" property of "Foo" class. I can't define type of this variable as "Human" interface from lib.ts.
In method "diffWithError" I make an error - use number "age" and string "name" in arithmetic operation, but neither IDE nor ts compiler know about this, because in this context, type of "this.human.name" is "any"
In method "diffWithTypingAndAutocoplete" I just use method "getHuman". IDE and compiler know about type of method result. This is "Human" interface and field "name" are "string". This method trigger an error when compiling sources.
I found this problem when I tried import .d.ts file of JS lib and I don't have ability to export needed interface. Can I somehow define valid type of "human" property without copy and paste code of "Human" interface whenever i want to define type (and without inline type definitions, like { name: string, age: number }).
I don not want to create instances of not exported classes, I just want type checking and autocomplete.
P.S. I try write this:
human: Human
compiler trigger an error: "error TS2304: Cannot find name 'Human'" (expected behavior)
P.S.S I try to do this with triple slash directive:
///<reference path="./lib.ts" />
but this not working too.
Sorry for my poor english and thanks for answers