TypeScript如何强类型转换ReadonlyMap?消除get返回值的undefined
问题:Map实现字典时get方法返回类型包含undefined的问题
我尝试用Map实现字典,已经定义了所有可能的key,并且使用了ReadonlyMap,但Map.get(key)的返回类型仍为valueType | undefined。
type dictKeys = 'key1' | 'key2' | 'key3' const dictObj:ReadonlyMap<DictKeys, string> = new Map<DictKeys, string>{ key1: 'value1', key2: 'value2', key3: 'value3', } satisfies Record<dictKeys, string> function testDictObj(key: dictKeys) { const res = dictObj[key] return res } const dictMap:ReadonlyMap<DictKeys, string> = new Map([ ['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3'], ]) function testDictMap(key: dictKeys) { const res = dictMap.get(key) return res }
我认为TypeScript应该能完成类型收窄:当存在无效key或Map中缺少key定义时给出警告,因此const res = dictMap.get(key)应仅返回string类型。使用普通对象时一切正常,但用Map实现字典更具语义化。我可以用断言!,但不够优雅。是否已有解决方法或自定义工具类型?
补充编辑:最终解决方案
已找到实现方案:将字典封装为自定义的ReadonlyMap子类,使get方法在传入合法key时仅返回值类型,不包含undefined:
function getEntries< T extends Record<PropertyKey, unknown>, K extends keyof T, V extends T[K] >(o: T) { return Object.entries(o) as [K, V][] } interface T_Dict<K extends PropertyKey, V> extends ReadonlyMap<K, V> {get(key: K): V} export class DictObject<K extends PropertyKey, V> extends Map<K, V> implements T_Dict<K, V>{ private constructor(obj: Record<K, V>) { super(getEntries(obj)) } public static create<K extends PropertyKey, V>(obj: Record<K, V>) { return new DictObject(obj) as T_Dict<K, V> } public override get(key: K): V { if (!this.has(key)) throw new Error('Wrong key!') return super.get(key) as V } }
内容的提问来源于stack exchange,提问作者Poul
相关产品推荐
相关产品推荐

