typescript - `interface`中的Typescript函数重载
问题描述
我第一次在 Typescript 中使用重载,并在interface
.
我想我正确理解了这个概念,因为这些示例编译时没有错误:
function test(): void;
function test(str: string): string;
// OK
function test(str?: string) {
if (typeof str === 'string') return str;
};
test(); // OK
test(''); // OK
class Test2 {
public test(): void;
public test(str: string): string;
// OK
public test(str?: string) {
if (typeof str === 'string') return str;
}
constructor() {
this.test(); // OK
this.test(''); // OK
}
}
但是,这些都抛出:
Type '() => void' is not assignable to type '{ (): void; (str: string): string; }'.
Type '(str: string) => string' is not assignable to type '{ (): void; (str: string): string; }'.
interface Test {
test(): void;
test(str: string): string;
}
const test1: Test = {
test: () => {}, // ERROR
};
const test2: Test = {
test: (str: string) => str, // ERROR
};
class Test implements Test {
constructor() {
this.test = () => {}; // ERROR
this.test = (str: string) => ''; // ERROR
}
}
我做错了什么,或者这是 Typescript 中的错误?
解决方案
您的失败案例正在失败,因为在每种情况下,您都分配了一个仅满足接口中定义的重载函数签名之一的实现。
这很难做到,因为您不能在任何给定对象上定义两个具有相同名称的属性。因此,就像您的function
声明一样,您需要提供一种满足两个函数签名的实现:
interface Test {
test(): void;
test(str: string): string;
}
const test: Test = {
test: (str?: string): any => {
if (typeof str === 'string') return str;
}
};
class Test implements Test {
constructor() {
this.test = (str?: string): any => {
if (typeof str === 'string') return str;
}
}
}
如此处所述,指定一个与两者都匹配且不重要(不可能?)的返回类型void
,string
因此需要使用any
.
推荐阅读
- android - Android / MySQL:如果当前活动为空,则阻止下一个活动
- python - 在 MacOS 上安装和配置最新的 python 3.8 时出现问题
- html - 嵌套元素的高度问题
- r - 如何从 RStudio 中查看 RSelenium 函数的帮助文档?
- python - np.gradient 是边界处后向和前向斜率的平均值吗
- c# - 空传播运算符返回 bool
- sql - 如何在sql中的触发器中进行嵌套?
- javascript - Semantic UI React - 无法在表格行上设置键属性
- r - 使用 for 循环用需要计算的方法填充矩阵。新手
- python - AttributeError:“DataFrame”对象没有属性“data”