提问人:Clifford B. Wolfe 提问时间:12/15/2022 最后编辑:Clifford B. Wolfe 更新时间:12/15/2022 访问量:297
在 typescript 中使用字符串访问 readonly 对象的属性
Use string to access properties of a readonly object in typescript
问:
const parent2 = {child: 'name'}
const index2: string = 'child';
const child3 = parent2[index2]
当我尝试访问时,出现以下错误child
parent2
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ child: string; }'.
No index signature with a parameter of type 'string' was found on type '{ child: string; }'
有没有一种简单的方法可以退货?parent2[index2]
'name' | undefined
处理嵌套的只读对象就更难了。 type 保持索引自动完成,它允许使用字符串访问属性,但构造类型很烦人。有没有一种简单的方法来访问allowStringIndex
nestedObject[grandParentIndex]?.[parentIndex]
const nestedObject = {grandParent: {name: 'grandparent', parent: {name: 'parent', child: {name: 'child'}}}} as const;
type child = {name: 'child', [key: string]: 'child' | undefined}
type parent = {name: 'parent', child: child}
type overrideParent = parent & {[key: string]: parent[keyof parent] | undefined}
type grandParent = {name: 'grandparent', parent: overrideParent}
type overrideGrandParent= grandParent & {[key: string]: grandParent[keyof grandParent] | undefined}
type allowStringIndex = {grandParent: overrideGrandParent} & {[key: string]: overrideGrandParent | undefined}
const castedObject = nestedObject as allowStringIndex;
const grandParentIndex: string = 'grandparent';
const parentIndex: string = 'parent'
const child = nestedObject[grandParentIndex]?.[parentIndex]?.['child']
const parent1 = castedObject[grandParentIndex]?.[parentIndex]
答:
0赞
jered
12/15/2022
#1
为什么要显式键入字符串常量,而不是让 TypeScript 推断值?您可以删除它们。另外,您似乎拼错了分配给的字符串,它应该不是吗?: string
grandParentIndex
"grandParent"
"grandparent"
// Don't do this
const parentIndex: string = 'parent'
// Do this
const parentIndex = 'parent';
评论
0赞
Clifford B. Wolfe
12/15/2022
人们在函数参数中将这些字符串文字作为字符串而不是泛型传递。有时这些字符串文字来自未键入的 angular 路由器
评论