You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 22:16:04