Quantcast
Channel: CNode:Node.js专业中文社区
Viewing all articles
Browse latest Browse all 14821

typescript关于检索属性类型的写法问题

$
0
0
class Funs {
  foo({ n, s }: { n: number, s: string }) {}
  bar({ s, b }: { s: string, b: boolean }) {}
}

const funs = new Funs();

function callFun<T extends keyof Funs> (name: T, ...params: Parameters<Funs[T]>) {
  return funs[name](params[0]);
}

callFun('bar', { b: true, s: 'sss'})

T"foo" | "bar", params[0]应该是根据T来确认是{ n: number, s: string }{ s: string, b: boolean }(从调用callFun时的代码提示中看是可以确认的)
下面调用函数时,funs[name]理论上应该可以确认到具体的函数是foo还是bar,但是到了传param的时候就报错了:

类型“{ s: any; b: any; } | { n: any; s: any; }”的参数不能赋给类型“{ n: any; s: any; } & { s: any; b: any; }”的参数。
  不能将类型“{ s: any; b: any; }”分配给类型“{ n: any; s: any; } & { s: any; b: any; }”。
    Property 'n' is missing in type '{ s: any; b: any; }' but required in type '{ n: any; s: any; }'.ts(2345)

ts好像在这里没法确认到函数和参数的具体类型,那么怎么写才能正确让ts识别出类型呢?


Viewing all articles
Browse latest Browse all 14821

Trending Articles