我想有一个类型的形式IA<T>
,像
interface IA<T> {
f: () => T | number;
x: boolean
}
不同的是,当x
是true
时,f
返回number
,而当x
是false
时,f
返回T
.这个是可能的吗?我试过了
interface IA<T> {
f: (this: IA<T>) => this['x'] extends true ? T : number;
x: boolean
}
但它不起作用:
const x0: IA<string> = { // error!
f: () => "hello",
x: true as const
}
我的目标是让以下代码正常工作:
if (x0.x === true) {
x0.f().toUpperCase(); // okay, it's a string
} else {
x0.f().toFixed(); // okay, it's a number
}
有可能吗?