如何在TypeScript中处理对象并添加新的字段?

作者站长头像
站长
· 阅读数 22

现有一个a对象和b对象,a对象为服务器返回的数据,b对象为对a对象加工后的数据。

类型为:

interface C {
  a: string
  b: string
  c: string
}

type A = Omit<C, 'c'>

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
回复
1个回答
avatar
test
2024-06-24

一个方式就是问题中所展示的, 但是不太灵活, 可以使用接口的任意属性:

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
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容