如何获得泛型可选函数参数的正确类型推断?

问题描述 投票:0回答:0

采取以下代码(游乐场链接):

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
是可选的情况下无法找到一种方法。

typescript types typescript-generics
© www.soinside.com 2019 - 2024. All rights reserved.