我正在检查typescript核心https://github.com/microsoft/TypeScript/blob/v4.0.5/lib/lib.es5.d.ts#L1966-L1970中的以下类型定义
这可以简化为:
interface Int8ArrayConstructor {
readonly prototype: Int8Array;
new(length: number): Int8Array;
new(array: ArrayLike<number> /*| ArrayBufferLike */): Int8Array;
new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;也就是说,从第二个new行可以删除ArrayBufferLike类型,对吗?
此外,如果使用ArrayBufferLike作为参数来调用new Int8Array(xyz),那么会将其解析为上述声明行中的哪些行?
发布于 2020-11-09 03:38:02
几乎不同的是,当您有一个类型为ArrayLike<number> | ArrayBufferLike (playground link)的变量时
interface ProposedInt8ArrayConstructor {
readonly prototype: Int8Array;
new(length: number): Int8Array;
new(array: ArrayLike<number> /*| ArrayBufferLike */): Int8Array;
new(buffer: ArrayBufferLike, byteOffset?: number, length?: number): Int8Array;
}
declare const ProposedConstructor: ProposedInt8ArrayConstructor
declare const def_buffer: ArrayBufferLike;
declare const may_be_either: ArrayBufferLike | ArrayLike<number>;
new Int8Array(def_buffer); // resolves to the second overload but 3rd would be valid
new Int8Array(may_be_either) // valid
new ProposedConstructor(def_buffer) // resolves to 3rd overload
new ProposedConstructor(may_be_either) // ERROR HERE!至于它们解析到哪个重载,你可以阅读上面代码块中代码行旁边的注释,或者通常将鼠标悬停在游乐场或其他支持智能感知的环境中的调用签名上:

所以它解决了第二个重载,因为没有额外的可选参数,就像你的提案一样:

它会解析到第三个。
https://stackoverflow.com/questions/64741740
复制相似问题