我有这个密码
type t = "a" | "b"
const o: { [key in t]?: Array<number> } = {}
interface Thing {
t: t;
}
const things: Array<Thing> = [{ t: "a"}]
for (const thing of things ) {
if (!(thing.t in o)) o[thing.t] = []
o[thing.t].push(1)
}
并得到错误Object is possibly 'undefined'.
TSPlayground链接
2条答案
按热度按时间ryhaxcpt1#
方法是
q5iwbnjs2#
在const o:{ [key in t]?:Array } = {}您添加了?从而使参数可选
像这样人也许能帮上忙