小编Naz*_*Orl的帖子

TypeScript。如何使用未导出的类型定义?

只要看一下这个打字稿代码:


图书馆

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”的类型为“任何” …

typescript typescript-typings

5
推荐指数
2
解决办法
1700
查看次数

标签 统计

typescript ×1

typescript-typings ×1