示例代码
type Base = {
name: string
}
type ExtA = {
address: string
}
type ExtB = {
streetName: string;
}
function handler<T extends Base>(input: T): T {return input}
/** how do I build an object up? */
let payload = {
name: "Aaron"
}
const addA = <T extends Base>(payload: T): T & ExtA => {
return {
...payload,
type: "a",
address: "123 Fake St"
}
}
const addB = <T extends Base>(payload: T): T & ExtB => {
return {
...payload,
type: "b",
streetName: "Main"
}
}
payload = addA(payload)
payload = addB(payload)
// type should be Base & ExtA & ExtB but it isn't
const wrongType = handler(payload)
// ^?
我期望payload
在通过操作函数时改变类型addA
,addB
但事实并非如此。如何让 TS 理解此变量的类型应该改变?