0

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

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

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

4

1 回答 1

1

I suggest to use strictNullCheck flag in compiler options. TS will start to look different on optional object. When you add | undefined to value definition strictNullCheck flag will force you to check is value is not undefined, or map type by as { id: number; name: string } syntax when you sure about returned type

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

于 2019-02-15T11:41:09.873 回答