假设存在接口RendererPayloadConnection:
interface RendererPayloadConnection<T> {
payload: Partial<{
[K in keyof T]: T[K] extends Callback<infer U>
? Tuple<U, any>
: T[K];
}>
}
type Callback<U> = (v: U) => void;
type Tuple<U, T> = [UnaryFunction<U, T>, (v: T) => void];
interface UnaryFunction<T, R> { (source: T): R; }
使用此接口可能会导致误报:
function map<T, R>(f: (arg: T) => R): UnaryFunction<T, R> {
throw 'not implemented';
}
class A {
output: Callback<string>;
}
const connection: RendererPayloadConnection<A> = {
payload: {
output: [
map(v => v.length),
n => n.length
]
}
};
(长度错误)
可以通过辅助功能“ tuplify”进行修复:
function tuplify<T, U>(mapper: UnaryFunction<T, U>, cb: Callback<U>): Tuple<T, U> {
return [mapper, cb];
}
const connection: RendererPayloadConnection<A> = {
payload: {
output: tuplify(
map(v => v.length),
n => n.length
)
}
};
如何描述接口RendererPayloadConnection进行正确的类型检查,而无需使用“ tuplify”帮助程序?