【发布时间】:2023-03-10 01:45:01
【问题描述】:
创建Record 时,keyof 会正确确定其密钥类型。但是当泛型参数扩展 Record 时,不会推断出键类型约束:
export type Dictionary<K extends number | string, V> = Partial<Record<K, V>>;
type MyDict = Dictionary<string, any>;
type Key = keyof MyDict; // Key correctly infered as string;
const myFunc = <D extends MyDict>(dict: D) => {
// keyof D incorrectly infered as string | number | symbol
type OtherDict = Dictionary<keyof D, number>;
};
有没有办法解决这个问题,并应用约束而不必断言每个 keyof D 实例的类型?
【问题讨论】:
标签: typescript dictionary generics record type-inference