TypeScript:Map返回Beat|undefined无法推入Beat数组的报错求助
解决TypeScript中Map.get返回undefined导致的类型不匹配问题
TypeScript里Map.get()方法的返回值默认是值类型 | undefined,因为编译时无法确保你要获取的键一定存在,哪怕你已经手动通过set()添加过该键。这就是你遇到Argument of type 'Beat | undefined' is not assignable to parameter of type 'Beat'错误的原因。
下面提供几种让Map返回确定类型的方案:
方案1:使用非空断言操作符!
直接告诉TypeScript,你确定该键对应的值一定存在,强制去掉undefined类型分支:
// 修改Staff构造函数中的push语句 beats.push(beatTypes.get('rest')!);
注意:如果后续代码不小心删除了beatTypes.set('rest', ...),运行时会触发Cannot read property...错误,仅适合能100%保证键存在的场景。
方案2:提前缓存确定类型的变量
将rest beat提前取出并断言类型,后续直接使用该变量,避免重复调用get():
// 在beatTypes定义后添加 const restBeat = beatTypes.get('rest')!; // Staff构造函数中直接用restBeat for (let index = 0; index <= 4 - beats.length; index++) beats.push(restBeat);
方案3:自定义Map子类(最安全)
封装一个强制返回确定类型的Map子类,键不存在时直接抛出错误,从根源避免undefined:
//*Beat class Beat { hexValue: number; symbol?: string; constructor(hexValue: number, symbol?: string) { this.hexValue = hexValue; this.symbol = symbol; } } // 自定义Map子类,确保get返回非undefined值 class BeatMap extends Map<string, Beat> { get(key: string): Beat { const value = super.get(key); if (!value) { throw new Error(`Beat type "${key}" does not exist`); } return value; } } //Empty beat let beatTypes = new BeatMap(); beatTypes.set('rest', new Beat(0x0000000000000000)); //*Staff class Staff { beats: Beat[]; constructor(beats: Beat[]) { if (beats.length > 4) beats = beats.slice(0, 4); else if (beats.length < 4) { const restBeat = beatTypes.get('rest'); for (let index = 0; index <= 4 - beats.length; index++) { beats.push(restBeat); } } this.beats = beats; } }
这种方案既能保证类型安全,又能在键意外缺失时及时抛出错误,方便调试和后续维护。
内容的提问来源于stack exchange,提问作者ReuJDon
相关产品推荐
相关产品推荐

