我正在try 从外部依赖项扩充接口.
原因是外部d.ts
文件没有指定完整的返回类型.
在下面的示例中,doStuff()
实际上存在于由Bar.giveList()
和Baz.giveList()
返回的对象上,但原始声明不包含此信息.
以下是使用declare global
的问题的重新构建(我实际上是在try 增加命名模块,但当在单个文件中使用两个declare global
块时,该问题似乎类似).
export type MyList<T> = T[] & {
doStuff(): void
}
declare global { // Original declaration from external dependency
export interface Bar {
giveList(): string[]
}
export interface Baz {
giveList(): string[]
}
}
declare global { // My attempt of refining some return types
export interface Bar {
giveList(): MyList<string>
}
export interface Baz {
giveList(): MyList<string>
}
}
let bar = {} as Bar
let baz = {} as Baz
let barbaz = {} as (Bar | Baz)
let barList = bar.giveList() // infered type: MyList<string> --- good
let bazList = baz.giveList() // infered type: MyList<string> --- good
let barbazList = barbaz.giveList() // infered type: string[] --- why not MyList<string>?
barList.doStuff() // good
barList[0] // good
bazList.doStuff() // good
bazList[0] // good
barbazList.doStuff() // ERROR: Property 'doStuff' does not exist on type 'string[]'.(2339)
barbazList[0] // good
既然Bar.giveList()
和Baz.giveList()
返回MyList<string>
,为什么(Bar|Baz).giveList()
不也返回MyList<string>
呢?