gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:32:38 32 4
gpt4 key购买 nike

我已经使用 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com