Naz*_*Orl 5 typescript typescript-typings
只要看一下这个打字稿代码:
图书馆
interface Human {
name: string;
age: number;
}
export default class HumanFactory {
getHuman(): Human {
return {
name: "John",
age: 22,
}
}
}
Run Code Online (Sandbox Code Playgroud)
索引
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;
}
}
Run Code Online (Sandbox Code Playgroud)
“ Foo”类的“人”属性中的问题。我无法从lib.ts中将此变量的类型定义为“人机”接口。
在方法“ diffWithError”中,我犯了一个错误-在算术运算中使用数字“ age”和字符串“ name”,但是IDE和ts编译器都不知道这一点,因为在这种情况下,“ this.human.name”的类型为“任何”
在方法“ diffWithTypingAndAutocoplete”中,我只使用方法“ getHuman”。IDE和编译器知道方法结果的类型。这是“人类”界面,字段“名称”是“字符串”。编译源代码时,此方法会触发错误。
我尝试导入JS lib的.d.ts文件时发现了此问题,但我没有能力导出所需的接口。每当我想定义类型时(如果没有内联类型定义,例如{name:string,age:number},是否可以以某种方式定义“ human”属性的有效类型而无需复制和粘贴“ Human”接口的代码)。
我不想创建未导出类的实例,只希望类型检查和自动完成。
PS我尝试写这个:
human: Human
Run Code Online (Sandbox Code Playgroud)
编译器触发错误:“错误TS2304:找不到名称'Human'”(预期行为)
PSS我尝试使用三斜杠指令执行此操作:
///<reference path="./lib.ts" />
Run Code Online (Sandbox Code Playgroud)
但这也不起作用。
对不起,我的英语不好,谢谢你的回答
I found a solution!
I make file human-interface.ts with this content:
import HumanFactory from './lib';
const humanObject = new HumanFactory().getHuman();
type HumanType = typeof humanObject;
export default interface Human extends HumanType {}
Run Code Online (Sandbox Code Playgroud)
Import of this interface in main file not execute creation of "HumanFactory" and type checking work properly.
Thanks for idea with typeof
更新
现在有了条件类型,无需解决方法即可完成:
type Human = ReturnType<HumanFactory['getHuman']>
Run Code Online (Sandbox Code Playgroud)
TS < 2.8 的解决方法
如果您无法更改lib.ts,您可以“查询”函数的返回类型getHuman。这有点棘手,因为打字稿目前没有为此提供任何直接的方法:
import HumanFactory from "./lib";
const dummyHuman = !true && new HumanFactory().getHuman();
type Human = typeof dummyHuman;
export class Foo {
human: Human;
// ...
}
Run Code Online (Sandbox Code Playgroud)
!true &&用于阻止new HumanFactory().getHuman()执行。
| 归档时间: |
|
| 查看次数: |
1700 次 |
| 最近记录: |