我已经使用 Typescript 工作了一个星期,现在我卡在 Interface 上了, 在这里我无法弄清楚Typescript如何将接口(interface)转换为javascript而编译后它没有出现在javascript代码中?
typescript
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
console.log("Customer Object ")
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
Javascript
var customer = {
firstName: "Tom",
lastName: "Hanks",
sayHi: function () { return "Hi there"; }
};
console.log("Customer Object ");
console.log(customer.firstName);
console.log(customer.lastName);
console.log(customer.sayHi());
最佳答案
接口(interface)等概念在纯 JavaScript 中不存在。接口(interface)仅存在于 TypeScript 中,用于保证使用和定义符合约定。
interface Post {
id: string;
title: string;
}
编译器使用上述定义来保证契约(Contract)得到遵守:
const goingToNewYork: Post = {
id: '123-455-222-111',
}
完成类型检查后,typescript 会简单地将 ts 编译为纯 javascript(省略声明)。
- 声明可以输出到单独的文件,通常称为
d.ts
: https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.html
关于javascript - 为什么 Typescript 接口(interface)不在 Javascript 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57131293/