【问题标题】:Best way to omit keys/items from an extended type in Typescript?从 Typescript 的扩展类型中省略键/项目的最佳方法?
【发布时间】:2021-10-27 13:14:43
【问题描述】:

假设我有一个类型:

type Thing = {
  foo: string;
  bar: string;
}

我扩展了它:

type ExtendThing = Omit<Thing, "bar"> & {foobar: string}

现在我想通过一个方法摆脱 foo:

const thing: Thing = {foo: "hello", bar: "world"}

const transform = (item: Thing): ExtendThing => {
  return {...item, foobar: `${item.foo}-${item.bar}`}
}

console.log(transform(thing))

打印:{ foo: 'hello', bar: 'world', foobar: 'hello-world' }

无论如何要在不更明确的情况下摆脱那个栏?

【问题讨论】:

  • TypeScript 类型只做类型检查。它不执行任何运行时执行。因此,您将需要显式编写脚本以从最终输出中排除 foo。带有类型错误的脚本仍然可以是有效的 JavaScript。
  • “现在我想通过一种方法摆脱 foo...” 正如我在对 this question 的回答中提到的(可能是骗局?):记住 TypeScript 是关于类型,而不是运行时值。 TypeScript 不能从对象中删除属性,它只能从对象的 type 中删除属性,如 TypeScript 所见。您必须编写运行时代码才能从对象中实际删除该属性(如我的答案所示)。
  • 返回 {foo: item.foo, foobar: ${item.foo}-${item.bar}}
  • 只是重复 T.J Crowder 所说的话。 TypeScript 永远不会改变你代码的行为,它只会给你类型提示。你实现了代码,当 TypeScript 无法推断出修改后的类型时,你必须告诉它它们会是什么样子。自己删除属性就行了,编译器的类型提示已经设置好了

标签: typescript


【解决方案1】:

您是否尝试过使用解构来获得构建对象所需的内容?

const transform = ({ foo, bar, ...rest }: Thing): ExtendThing => {
  return { ...rest, foo, foobar: `${foo}-${bar}` };
};

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2010-11-01
    • 1970-01-01
    • 2020-08-09
    相关资源
    最近更新 更多