javascript - 为什么 Typescript 接口(interface)不在 Javascript 中呈现

标签 javascript typescript

我已经使用 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',
}

enter image description here

完成类型检查后,typescript 会简单地将 ts 编译为纯 javascript(省略声明)。

关于javascript - 为什么 Typescript 接口(interface)不在 Javascript 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57131293/

相关文章:

angular - 服务中声明的函数获取 "is not a function"

javascript - 如果我不知道他们的 id,如何检查有多少个复选框被选中

javascript - 用 esc 键隐藏一个 div,然后关闭点击?在查询中

javascript - 是的,当 .required() 为 false 时,会继续在同一个属性上运行验证器

javascript - 我需要在 Node js 或 AWS 中编写 cron 作业吗?

angular - Firestore 从 Angular ​​获取单个数据

node.js - VS Code 无法识别 Jest,使用 Intellisense 下划线

每个文件夹的 Typescript 模块

javascript - HTTP 调用结束时的事件调用

javascript - 在 Typescript 中使用 `: Interface` 和 `as Interface` 有什么区别?