【发布时间】:2021-10-17 16:52:37
【问题描述】:
我如何将 {...a,...b} 的等价物编写为 typescript 4.4+ 中的通用函数。我知道a 和b 都是记录,但事先不知道它们是什么。我想创建一个泛型类型,将任意函数限制为 {...a,...b} 操作。
不起作用的示例:
type Rec = Record<string,unknown>
type ExtendRec = <X extends Rec, Y extends X>(x: X) => Y
// or <X extends Rec, Y extends Rec>(x: X) => Y&X
const addA:ExtendRec = <X extends Rec>(x:X) => ({...x, a: 'a'})
const addB:ExtendRec = <X extends Rec>(x:X) => ({...x, b: 'b'})
const addC:ExtendRec = <X extends Rec>(x:X) => ({...x, c: 'c'})
const blank = {} // expected {}
const a = addA(blank) // expected {a:string}, actual:{}
const ab = addB(a) // expected {a:string,b:string}, actual:{}
const abc = addC(ab) // expected {a:string,b:string,c:string}, actual:{}
addA、addB、addC 函数的类型错误是:
Type '<X extends Rec>(x: X) => X & { c: string; }' is not assignable to type 'ExtendRec'.
Type 'X & { c: string; }' is not assignable to type 'Y'.
'X & { c: string; }' is assignable to the constraint of type 'Y', but 'Y' could be instantiated with a different subtype of constraint 'Record<string, unknown>'.
令人费解的是,如果我只是删除 ExtendRec 作为函数注释,它就可以工作,因此 typescript 已经能够正确推断对象分配操作,但我不能编写一个通用函数类型来约束任意函数扩展操作。
【问题讨论】:
-
Rec声明在哪里? -
您说
a和b是记录,但它们在您的代码中被分配了字符串? -
添加了推荐。 a、ab 和 abc 反映了结果应该具有哪些属性。
标签: typescript