我已经使用TypeScript一周了。我被困在interfaces上;这里我无法弄清楚TypeScript如何将接口转换为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());
2条答案
按热度按时间bvpmtnay1#
像接口这样的概念在纯JavaScript中是不存在的。接口只存在于TypeScript中,它们用于保证用法和定义遵守合约。
编译器使用上面的定义来保证遵守契约:
一旦完成了类型检查,typescript就简单地将ts编译成普通的javascript(省略了声明)。
d.ts
:https://basarat.gitbooks.io/typescript/docs/types/ambient/d.ts.htmlk5ifujac2#
就像我的文件名是= interface1.ts,所以首先你必须在终端中写入你的文件名,比如=>(1)tsc interface1.ts然后输入,之后,=>(2)node interface1.js
然后它会将typescript转换为JavaScript,你会得到输出***,但首先你必须在vs代码中安装typescript,commit is=>npm install -g typescript