例如
enum Size {
Small: 'small'
Medium: 'medium'
Large: 'large'
}
enum Weekday {
Monday: 'Monday'
Tuesday: 'Tuesday'
...
}
// Only need Size.Medium and Size.Large, and anywhere from 1 to 7 Weekday entries
const mapping: { [size in Size]?: { [weekday in Weekday]? : MenuType } = {
[Size.Medium] : { Weekday.Tuesday : <menuObject> }
[Size.Large] : {
Weekday.Monday : <menuObject>
Weekday.Friday : <menuObject>
}
}
当我尝试使用const menu = mapping[Size.Large][Weekday.Monday]
获取菜单时,我得到一个错误说Object is possibly undefined
。
创建这个映射的最好方法是什么,使它仍然是强类型的?
正如@Linda Paiste所说,这是正常的行为。
当您使用?:
操作符时,它表示以下键方式是否被定义(未定义)。
所以当TypeScript遍历你的mapping
对象时,不确定Size.Large
后面的数据是否会被定义。这就是为什么它会给你一个错误。
您的选择是:
或者你让每个键都是强制性的,比如:
游乐场
enum Size {
Small = 'small',
Medium = 'medium',
Large = 'large',
};
enum Weekday {
Monday = 'Monday',
Tuesday = 'Tuesday',
Friday = 'Friday',
};
type MenuType = {};
const mapping: {
[size in Size]: {
[weekday in Weekday] : MenuType;
};
} = {
[Size.Small]: {
[Weekday.Monday]: {},
[Weekday.Tuesday]: {},
[Weekday.Friday]: {},
},
[Size.Medium]: {
[Weekday.Monday]: {},
[Weekday.Tuesday]: {},
[Weekday.Friday]: {},
},
[Size.Large]: {
[Weekday.Monday]: {},
[Weekday.Tuesday]: {},
[Weekday.Friday]: {},
},
};
const menu = mapping[Size.Large]?.[Weekday.Monday];
处理潜在的未定义的值,例如:
游乐场
enum Size {
Small = 'small',
Medium = 'medium',
Large = 'large',
};
enum Weekday {
Monday = 'Monday',
Tuesday = 'Tuesday',
Friday = 'Friday',
};
type MenuType = {};
const mapping: {
[size in Size]?: {
[weekday in Weekday]? : MenuType;
};
} = {
[Size.Medium]: {
[Weekday.Tuesday]: {},
},
[Size.Large]: {
[Weekday.Monday]: {},
[Weekday.Friday]: {},
},
};
const menu = mapping[Size.Large]?.[Weekday.Monday];