使用对象作为词典时如何确保类型安全性和详尽性?

问题描述 投票:0回答:1

这是一个在运行时失败的代码示例:

interface IDict {
  [key: string]: { id: number; name: string };
}
const something = (unknownKey: string) => {
  const aDict: IDict = {};
  const a = aDict[unknownKey];
  console.log(a.name);
};

字典的正确类型是什么,以便TS强制我们在使用它时总是进行空检查?

typescript
1个回答
1
投票

我建议在编译器选项中使用strictNullCheck标志。 TS将开始在可选对象上看起来不同。当您将| undefined添加到值定义时,strictNullCheck标志将强制您检查值是否未定义,或者当您确定返回类型时,通过as { id: number; name: string }语法映射类型

interface IDict {
  [key: string]: { id: number; name: string } | undefined;
}

const something = (unknownKey: string) => {
    const aDict: IDict = {};
    const a = aDict[unknownKey];
    console.log(a.name); // error
    if (a !== undefined) {
        console.log(a.name); // ok
    }
    console.log((a as { id: number; name: string }).name); //also ok
};

Playground

© www.soinside.com 2019 - 2024. All rights reserved.