如何在TypeScript中定义支持动态属性的Interface适配自定义数据结构
你原有写法不生效的核心原因是你把根数据定义为了数组类型,数组本身不存在foo/name这类自定义属性,自然无法直接通过.属性名的方式访问子字段。
方案1:适配你需要的直接属性访问写法(推荐)
直接把根数据的类型调整为动态属性对象,不需要用数组包裹:
interface TestSubInterface { text: string; anotherThing: string; } export interface TestRootInterface { // 动态属性,键为任意字符串,值为子接口类型 [propName: string]: TestSubInterface; } // 声明变量时直接用根接口类型,不用数组 let test: TestRootInterface = { name: { text: 'something', anotherThing: 'something' }, foo: { text: 'something', anotherThing: 'something' }, whatever: { text: 'something', anotherThing: 'something' } }; // 可以直接用你期望的写法修改数据 test.foo.text = "another text for example";
方案2:保留原有数组结构的处理方式
如果你必须保留原始的数组结构,访问时需要先匹配到对应键的数组项:
interface TestSubInterface { text: string; anotherThing: string; } export interface TestArrayItemInterface { [propName: string]: TestSubInterface; } // 根数据为数组类型 let test: TestArrayItemInterface[] = [ { name: { text: 'something', anotherThing: 'something' } }, { foo: { text: 'something', anotherThing: 'something' } }, { whatever: { text: 'something', anotherThing: 'something' } }, ]; // 先找到对应键的数组项再修改 const targetItem = test.find(item => 'foo' in item); if (targetItem) { targetItem.foo.text = "another text for example"; }
内容的提问来源于stack exchange,提问作者CVO
相关产品推荐
相关产品推荐

