问题是
playerById
是可选的(可能是
undefined
)或者
null
。
和
null['skills']
无效,这意味着:
type A = { skills: string[] } | null
type B = A['skills'] // also not valid
因此,您需要明确删除
未定义的
和
无效的
从类型开始,然后再进行深入研究。
幸运的是,typescript附带了一个实用程序类型,用于
NonNullable<T>
。
type A = { skills: string[] } | null
type B = NonNullable<A>['skills'] // now works fine
所以现在只需将其应用于您自己的类型,如下所示:
let skills: NonNullable<PlayerByIdQuery["playerById"]>["skills"] = [
{
__typename: 'PlayerSkill',
description: 'Fancy punch',
id: 'abc123',
playerId: 'def456'
}
]
See playground