Typescript 保护地图访问的类型脚本错误TS2532

Typescript 保护地图访问的类型脚本错误TS2532,typescript,Typescript,Typescript将下面的两个conn.get(aa)标记为TS2532错误。但是这两个访问都由if(conn.has(aa))保护,因此我推断get是有效的,而不是未定义的 const conn: Map<string, {from: string[]; to: string[]}> = new Map(); const aa = "aa"; if(conn.has(aa)) conn.get(aa).to.push("bb"); conn.set("aa", {from: [

Typescript将下面的两个
conn.get(aa)
标记为TS2532错误。但是这两个访问都由
if(conn.has(aa))
保护,因此我推断
get
是有效的,而不是未定义的

const conn: Map<string, {from: string[]; to: string[]}> = new Map();
const aa = "aa";
if(conn.has(aa)) conn.get(aa).to.push("bb");

conn.set("aa", {from: [], to: []});
if(conn.has(aa)) conn.get(aa).to.push("bb");

typescript在
conn.get(aa)
上投诉。我看不见的隐藏问题在哪里?谢谢

问题在于
conn.has(aa)
是一个javascript函数,
conn.get(aa)
type是一个TypeScript功能。因此,您不能使用has来确保get将返回notundefined


您应该在if之后断言get,这不会在bundle中进行任何更改,但会告诉编译器该值已被检查
(conn.get(aa)!)。to

好吧,没有使用
has(key)
进行检查的技巧,这似乎符合typescript控制流:
const getaa=conn.get(aa);如果(getaa)getaa.推送(“bb”)这是一个可接受的解决方案?现在请理解!我在想has和get之间的某种联系。那么友好的‘!’或者直接检查get是解决方案。谢谢
if(conn.has(aa) && conn.get(aa)) conn.get(aa).to.push("bb");