这两者之间有什么区别(如果有的话):
declare interface SomeInterface {
//members here
}
并且:
interface SomeInterface {
//members here
}
?
这两者之间有什么区别(如果有的话):
declare interface SomeInterface {
//members here
}
并且:
interface SomeInterface {
//members here
}
?
declare
关键字通常用于类型定义中,用来描述在JavaScript代码中已经存在的类或变量。
declare interface
和interface
没有区别,因为:
declare interface
定义在JavaScript代码中的接口;declare interface
和interface
在语法上是相等的。interface
还包括declare interface
。你有关于“声明的接口不会被缩小”的来源或引用吗?你是想到了出现在.d.ts
输出文件中的declare interface
(而不是.js
输出文件)吗?如果是这样,那么你会发现.d.ts
文件中既有declare interface
类型也有interface
类型。未使用类型的删除根本不是由TypeScript完成的,而是由其他地方完成的。 - Dai为了回答这个问题,要理解的一个概念是接口声明合并。在TypeScript中,接口声明合并的工作原理如下:
每当我们多次声明一个接口(带或不带declare
关键字),它们将被合并在一起。这意味着接口现在具有合并在一起的两个接口的属性。最好通过以下示例来理解:
// Usually this interface would be defined in another file
// or package already
interface foo { num1: number }
// Because the interface foo is already defined TS will apply
// interface declaration merging
declare interface foo{num2: number}
// Declare keyword makes it more explicit that is was defined
// somewhere else, it adds n
let fooObj: foo = { num1: 1 }
// Typescript will give the following error:
// Property 'num2' is missing in type '{ num1: number; }'
// but required in type 'foo'.(2741)
// It requires the property num2 because after the interface merging
// the interface contains both num1: number, and num2: number properties
// This interface declaration merging functionally similar to
// the foo interface above, just without the declare keyword
interface bar{ string1: string }
interface bar{ string2: string }
let barObj: bar = { string1: 'hi', string2: 'hithere' }
declare
关键字在接口之前的作用请注意,declare interface
只是更明确地说明该接口在其他地方定义(比如其他文件、包等) ,没有添加任何额外的功能。
同时还要注意,接口仅仅是为了给TS编译器提供附加类型信息,在编译后的JS中并不存在。上面的代码编译后会变成以下的JS:
"use strict";
let fooObj = { num1: 1 };
let barObj = { string1: 'hi', string2: 'hithere' };