为同一个对象分配不同的接口

发布于 2025-01-14 16:14:47 字数 800 浏览 5 评论 0原文

我有一个 Typescript 项目,我想在具有不同接口的多个函数之间传递相同的对象,

这些是接口:

export interface TestModel {
  fileName:string,
  year:number,
  country:string
}
export interface Test2Model {
  fileName:string,
  year:number
}

这是生成对象的第一个函数,并调用第二个函数,将生成的对象传递给它:

function test1() {
  let fileData:TestModel = {
    fileName:'fileName',
    year:2022,
    country:'Spain'
  }

  test2(fileData)  
}

test1();

这是第二个函数函数:

function test2(fileData:Test2Model) {
  console.log(fileData)
}

这是我在第二个函数中得到的:

{fileName: "fileName", year: 2022, country: "Spain"}

这是我想要收到的:

{fileName: "fileName", year: 2022}

我的问题:是否可以自动生成适应 Test2Model 接口的第二个对象而不创建新对象?

I have a Typescript project in which I want to pass the same object between several functions with a different interface

These are the interfaces:

export interface TestModel {
  fileName:string,
  year:number,
  country:string
}
export interface Test2Model {
  fileName:string,
  year:number
}

This is the first function that generates the object and calls the second function passing it the generated object:

function test1() {
  let fileData:TestModel = {
    fileName:'fileName',
    year:2022,
    country:'Spain'
  }

  test2(fileData)  
}

test1();

This is the second function:

function test2(fileData:Test2Model) {
  console.log(fileData)
}

This is what I get in the second function:

{fileName: "fileName", year: 2022, country: "Spain"}

This is what I want to receive:

{fileName: "fileName", year: 2022}

My problem: is it possible to automatically generate the second object adapted to the Test2Model interface without creating a new object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

大海や 2025-01-21 16:14:47

你需要删除属性,类型不能改变对象。使用删除关键字,例如

delete fileData.country

//then pass it to test2 function

You need to delete the property, the type can't change the object. Use delete keyword like

delete fileData.country

//then pass it to test2 function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文