如何在TypeScript中处理对象并添加新的字段?-灵析社区

一只tomatoo

现有一个a对象和b对象,a对象为服务器返回的数据,b对象为对a对象加工后的数据。 类型为: interface C { a: string b: string c: string } type A = Omit type B = C 由于`A`数据并没有`c`字段, 我要加`c`字段,但是加`c`字段又提示`A`没有`c`字段,如: a.c = 'abc' // 报错类型A上不存在属性c b = a 还是说我直接把类型定义为: interface C { a: string b: string c?: string } type A = C type B = C

阅读量:15

点赞量:0

问AI
一个方式就是问题中所展示的, 但是不太灵活, 可以使用接口的任意属性: interface Person { name: string; age?: number; [propName: string]: any; } let tom: Person = { name: 'Tom', gender: 'male' }; 使用 "[propName: string]" 定义了任意属性取 string 类型的值。 需要注意的是,一旦定义了任意属性,那么确定属性和可选属性的类型都必须是它的类型的子集: interface Person { name: string; age?: number; [propName: string]: string; } let tom: Person = { name: 'Tom', age: 25, gender: 'male' }; // index.ts(3,5): error TS2411: Property 'age' of type 'number' is not assignable to string index type 'string'. // index.ts(7,5): error TS2322: Type '{ [x: string]: string | number; name: string; age: number; gender: string; }' is not assignable to type 'Person'. // Index signatures are incompatible. // Type 'string | number' is not assignable to type 'string'. // Type 'number' is not assignable to type 'string'. «"http://ts.xcatliu.com/basics/type-of-object-> interfaces.html" (https://link.segmentfault.com/?enc=HTiQkTqmYAJzzXtJJJvNVg%3D%3D.gC07qgJFXbaWfFwkKdIJh8DqIk9sFAL%2BXN3phdTBBOi5zzHaJ%2BR%2FwFFjOqujv%2F4i1tE9SQDRjOVZ6z2ioqVbJw%3D%3D)»