Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么Typescript接口不能在Javascript中呈现_Javascript_Typescript - Fatal编程技术网

为什么Typescript接口不能在Javascript中呈现

为什么Typescript接口不能在Javascript中呈现,javascript,typescript,Javascript,Typescript,我已经用Typescript工作了一个星期,现在我被卡住了,在这里我无法弄清楚Typescript是如何将一个接口转换成javascript的,而编译后它不会出现在javascript代码中 Typescript interface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastNa

我已经用Typescript工作了一个星期,现在我被卡住了,在这里我无法弄清楚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())  
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());
Javascript

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())  
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());

普通JavaScript中不存在接口之类的概念。接口仅存在于TypeScript中,用于保证用法和定义符合合同

interface Post {
  id: string;
  title: string;
}
编译器使用上述定义来保证合同得到遵守:

const goingToNewYork: Post = {
  id: '123-455-222-111',
}

完成类型检查后,typescript只需将ts编译为纯javascript(省略声明)

  • 声明可以输出到单独的文件,通常称为
    d.ts
它不会将接口转换为JS。TS只存在于编译时,在运行时它只存在于JS中。