【发布时间】:2026-01-05 07:25:02
【问题描述】:
我想使用 typescript never 类型,以确保我已经检查了接口的所有可能实现。 Here is the code:
interface MyInterface {
a: string;
b: number;
}
class MyClass1 implements MyInterface {
a: string;
b: number;
constructor() { }
}
class MyClass2 implements MyInterface {
a: string;
b: number;
constructor() { }
}
function foo(arg: MyInterface) {
if (arg instanceof MyClass1) {
} else if (arg instanceof MyClass2) {
} else {
assertNever(arg);
}
}
function assertNever(value: never): never {
throw Error(`Unexpected value '${value}'`);
}
但我得到了错误:'MyInterface' 类型的参数不可分配给'never' 类型的参数。
有什么办法可以解决这个问题吗?
【问题讨论】:
标签: typescript class interface