我想创建一个可以处理泛型特征对象的函数。代码如下
interface ComplexTypeMap {
featureA: { name: string },
featureB: { age: number }
}
function testComplexTypeMap<K extends keyof ComplexTypeMap>(
typeName: K, value: ComplexTypeMap[K]) { }
const featureA = { name: 'John' };
const featureB = { age: 18 };
testComplexTypeMap('featureA', featureA);
testComplexTypeMap('featureA', featureB); // #marker1, good catch, expected behavior
interface Settings<K extends keyof ComplexTypeMap> {
featureName: K,
value: ComplexTypeMap[K]
}
function testComplexTypeMapSetting<K extends keyof ComplexTypeMap>
(typeName: K, value: Settings<K>) { }
const settingsA: Settings<'featureA'> = { featureName : 'featureA', value : featureA};
const settingsB: Settings<'featureB'> = { featureName : 'featureB', value : featureB};
testComplexTypeMapSetting('featureA', settingsA);
testComplexTypeMapSetting('featureA', settingsB); // #marker2, why not catch the error, unexpected
在 marker1 处,错误是预期的,而且很好。所以我预计,应该在marker2上抛出错误,但它没有。奇怪的是,实际上打字稿知道我应该在marker2中使用的类型,显示出一些智能感知,如附图所示。但它只是接受 settingsB 而不会发出任何警告。这是为什么?上面的代码可以在打字稿操场上运行