typescript - 如何将 2 个部分合并为 Typescript 中的一个完整对象?

标签 typescript

See a playground of this question here

我有一个需要所有 Prop 的界面。但是,创建对象是一个两步过程。因此,我计划创建该对象的 2 个 Partial 版本,然后将它们合并在一起以满足非部分接口(interface)。示例:

interface IComplete {
    a: string,
    b: string
}

const part1: Partial<IComplete> = {
    a: 'hello'
}

const part2: Partial<IComplete> = {
    b: 'world'
}

const together: IComplete = {
    ...part1,
    ...part2
}

即使 together 总是完整的,编译器也会提示:

Type '{ a?: string; b?: string; }' is not assignable to type 'IComplete'. Property 'a' is optional in type '{ a?: string; b?: string; }' but required in type 'IComplete'.

是否有推荐的方法来实现这一点?对我而言,IComplete 接口(interface)不是是部分的,这一点很重要。 IE。 Prop a 和 b 永远不会为 null 或未定义。

最佳答案

@RyanCavanaugh 的回答很好。一种让类型推断完成其工作的方法,同时仍然获得编译器的好处确保 part1part2Partial<IComplete>是使用如下辅助函数:

interface IComplete {
  a: string,
  b: string,
  c: (x: string) => number,
  d: (x: number) => string
}

// helper function
const asPartialIComplete = <T extends Partial<IComplete>>(t: T) => t;

const part1 = asPartialIComplete({
  a: 'hello',
  c: (x) => x.length
})

const part2 = asPartialIComplete({
  b: 'world',
  d: (x) => x + ""
});

const together: IComplete = {
  ...part1,
  ...part2
}

在上面,part1part2受制于 asPartialIComplete有效Partial<IComplete>对象(因此 cd 方法的参数分别被推断为 stringnumber)。但是 part1 的类型和 part2足够窄,编译器可以意识到 typeof part1 & typeof part2IComplete .

希望对您有所帮助。祝你好运!

关于typescript - 如何将 2 个部分合并为 Typescript 中的一个完整对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51275395/

相关文章:

typescript - 是否可以更改 Playwright 中 toHaveScreenshot() 的路径?

css - 如果文本溢出屏幕,如何动态更改使用 css 显示的文本的位置

javascript - 在类型转换数组上使用 forEach 时遇到问题

Typescript 未检测到非法参数

javascript - 如何在浏览器扩展上下文中通过 TypeScript 访问全局变量(如果可能,部分输入)

Angular : Observable not working

javascript - Mongoose 文本搜索未返回任何结果

javascript - typescript /Knex : Cannot use import statement outside a module

typescript 类型 'never' : how to use for object fields?

javascript - 循环直到在 Javascript 中找到一个空数组