取以下代码(playground link):
function combine<F extends Record<string, string>, B extends Record<string, string>>(foo: F, bar?: B) {
const retVal = {
...foo,
...bar
}
return retVal
}
const test = combine({
one: 'One',
}, {
two: 'Two',
})
function testKey<T extends Record<string, string>>(foo: T, bar: keyof T) { }
testKey(test, 'one') // Valid
testKey(test, 'two') // Valid
testKey(test, 'three') // Shouldn't be valid
第19行应该是无效的,但它是有效的.如果我将鼠标悬停在retVal
上方,则推断的类型如下:
const retVal: F & {
[x: string]: string;
}
但我不确定为什么会有这样的推断.这是一种过于宽容的做法.如果我将其更改为bar
不是可选的,则推断retVal
的类型如下:
const retVal: F & B
这是我想要的类型推断,但当bar
是可选的时候,我想不出一种方法来获得它.