为什么TypeScript不检查分配类型或从对象查找进行分配时未定义

问题描述 投票:1回答:1
type Whatever = {
  name: string;
};
const map: { [key: string]: Whatever } = {};

// Errors
const a: Whatever = {}; // name is required in type Whatever
const b: Whatever = undefined; // undefined not assignable

// No Errors
const c: Whatever = map["not-found"]; // undefined
const d: Whatever = map["not-found"] || {}; // {}

或看看here

我希望cd的分配无法通过类型检查。

typescript typechecking
1个回答
0
投票

如果您的地图包含Whatever?,则您的代码行为正确。它确实进行类型检查;您只需告诉它map包含任何key: string的任何实例。

const map: { [key: string]: Whatever? } = {};

当然,有无限可能的字符串键,因此您无法为它们全部定义一个值,但是您已经以这种方式声明了您的类型,而Typescript不会纠正您。

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