TypeScript 为核心类型声明合并
TypeScript declare merge for core types
我如何使用 import 为内置类型声明合并。
实际上,我正在尝试对本文档中的每条指令进行接口声明合并:
https://www.typescriptlang.org/docs/handbook/declaration-merging.html
- 当我在没有任何导入的情况下进行合并时,它有效:
interface Function {
applyParams?(aa: string[]): string
}
function f() {}
const a: Function = f
a.applyParams && a.applyParams(["1", "2"]);
- 但是,如果我在文件开头添加导入语句,则会出现错误,如下例所示:
import { MyType } from "./MyType";
interface Function {
applyParams?(aa: string[]): MyType;
}
function f() {}
const a: Function = f;
a.applyParams && a.applyParams(["1", "2"]);
错误是:
TS2559:类型“() => void”与类型 'Function' 没有共同的属性。
如果您将定义包装在全局块中,它会起作用。
import { MyType } from "./MyType";
declare global {
interface Function {
applyParams?(aa: string[]): MyType;
}
}
function f() {}
const a: Function = f;
a.applyParams && a.applyParams(["1", "2"]);
这可能是因为 TypeScript 处理带有和不带有 import 语句的文件的方式不同。具有导入的文件被视为模块并具有局部作用域,而其他文件可被视为声明文件并默认具有全局作用域。
我如何使用 import 为内置类型声明合并。
实际上,我正在尝试对本文档中的每条指令进行接口声明合并: https://www.typescriptlang.org/docs/handbook/declaration-merging.html
- 当我在没有任何导入的情况下进行合并时,它有效:
interface Function {
applyParams?(aa: string[]): string
}
function f() {}
const a: Function = f
a.applyParams && a.applyParams(["1", "2"]);
- 但是,如果我在文件开头添加导入语句,则会出现错误,如下例所示:
import { MyType } from "./MyType";
interface Function {
applyParams?(aa: string[]): MyType;
}
function f() {}
const a: Function = f;
a.applyParams && a.applyParams(["1", "2"]);
错误是: TS2559:类型“() => void”与类型 'Function' 没有共同的属性。
如果您将定义包装在全局块中,它会起作用。
import { MyType } from "./MyType";
declare global {
interface Function {
applyParams?(aa: string[]): MyType;
}
}
function f() {}
const a: Function = f;
a.applyParams && a.applyParams(["1", "2"]);
这可能是因为 TypeScript 处理带有和不带有 import 语句的文件的方式不同。具有导入的文件被视为模块并具有局部作用域,而其他文件可被视为声明文件并默认具有全局作用域。