有没有办法声明一个 Typescript 函数,如果传入的值是静态已知为特定类型的,则会导致 tsc 拒绝对它的调用,否则接受调用?
在下面的示例中,我有一个包装传递值的函数,但如果传入的值已被包装,我希望该函数静态拒绝调用。
此时,我能做到的最好的事情是,如果传入了包装值,则使静态分析器期望函数返回的值为“从不”。
class WrappedValue<T> {
constructor(readonly value:T) {}
}
function wrap<T>( value:T) : WrappedValue<T> {
return new WrappedValue(value)
}
type SingleWrapped<RR> = RR extends WrappedValue<unknown> ? never : WrappedValue<RR>;
function wrap_strict<TT>(retvalIn:TT) : SingleWrapped<TT> {
if (retvalIn instanceof WrappedValue) {
throw new Error('strict failure')
} else {
//@ts-expect-error TODO: How do we avoid the error below: TS2322: Type 'WrappedValue<TT>' is not assignable to type 'SingleWrapped<TT>'.
let retval : SingleWrapped<TT> = wrap<TT>(retvalIn);
return retval;
}
}
const xx1 = wrap_strict(2)
xx1.value
const xx2 = wrap_strict(wrap(3))
// TODO: is there a way to cause tsc to complain on the line above rather than the line below?
xx2.value // tsc complains about this line because xx2 is of type never