TypeScript。如何使用未导出的类型定义?
只要看看这个打字稿代码:TypeScript。如何使用未导出的类型定义?
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;
}
}
在 “富” 的 “人性化” 属性的问题类。我无法将此变量的类型定义为来自lib.ts的“Human”接口。
在方法“diffWithError”我做了错误 - 在算术运算使用号码“年龄”和字符串“名”,但既不IDE也不TS编译器知道这一点,因为在这种情况下,键入“this.human的。名称“是”any“
在”diffWithTypingAndAutocoplete“方法中,我只使用方法”getHuman“。 IDE和编译器知道方法结果的类型。这是“人”界面,字段“名称”是“字符串”。此方法在编译源时会触发错误。
我发现这个问题,当我试图导入JS库的.d.ts文件,我没有能力导出所需的接口。无论何时我想定义类型(并且没有内联类型定义,如{name:string,age:number}),我是否可以以某种方式定义有效类型的“人类”属性,而无需复制和粘贴“Human”接口的代码。
我不想创建未导出的类的实例,我只想要类型检查和自动完成。
P.S.我试着写:
human: Human
编译器触发的错误:“错误TS2304:找不到名称‘人’”(预期的行为)
PSS我尝试用三重斜线指令,要做到这一点:
///<reference path="./lib.ts" />
但是这不起作用。
对不起,我的英语不好,感谢您的回答
如果你不能改变lib.ts可以“查询”返回getHuman
函数的类型。
import HumanFactory from "./lib";
const dummyHuman = !true && new HumanFactory().getHuman();
type Human = typeof dummyHuman;
export class Foo {
human: Human;
// ...
}
!true &&
是用来防止new HumanFactory().getHuman()
执行:因为目前的打字原稿没有提供这方面的任何直接的方法,这是一个有点棘手。
需要导出Human
以便它是可见的 - 和使用 - 从index.ts
以及(如HumanFactory
)。不要使用默认的出口,但“命名出口”,即尝试这种
export interface Human {
name: string;
age: number;
}
export class HumanFactory {
getHuman(): Human {
return {
name: "John",
age: 22,
}
}
}
在index.ts
import { Human, HumanFactory} from "./lib";
**编辑**
如果你不能改变lib.d.ts
然后重新Human
并使用双铸造即
import HumanFactory from "./lib";
interface Human {
name: string;
age: number;
}
export class Foo {
human: Human; // <= change here
constructor() {
const factory = new HumanFactory();
this.human = factory.getHuman() as any as Human; // <= double casting
}
diffWithError(age: number): number {
return age - this.human.name;
}
diffWithTypingAndAutocoplete(age: number): number {
const factory = new HumanFactory();
return age - factory.getHuman().name;
}
}
我无法编辑'lib.ts'。在我的项目中,这是在.d.ts文件中外部库的类型定义。 –
@NazikOrl看到我的编辑替代解决方案 –
感谢您的答案。我发现[另一个解决方案](https://stackoverflow.com/a/46774999/8779223)对我来说可接受 –
我找到了解决方案!
我把文件人类interface.ts与此内容:主文件
import HumanFactory from './lib';
const humanObject = new HumanFactory().getHuman();
type HumanType = typeof humanObject;
export default interface Human extends HumanType {}
导入这个接口的不执行“HumanFactory”的创作和类型检查正常工作。
感谢您的想法typeof
不幸的是,它不起作用:错误TS2322:类型'Human'不能分配给'false'类型。当我在构造函数 –
中尝试这个'this.human = factory.getHuman()'你使用哪种版本的打字稿? –