这种情况在 TypeScript 中为什么会发生?(联合类型)

huangapple go评论51阅读模式
英文:

Why does this happen in typescript? (union types)

问题

这可能是重复的,但我找不到答案。

我有这种类型:

type A = {
    prop2: string;
    prop1: string;
} | {
    prop3: string;
    prop1: string;
}

正如你所看到的,它有一个共享的 prop 和 2 个不同的 props。但是我可以这样使用它:

const a: A = {
  prop1: '',
  prop2: '',
  prop3: '',
};

而且它奏效!

但后来我需要检查 a 是否有 prop2 和 prop3 才能使用它:

a.prop1 = '';
// @ts-expect-error
a.prop2 = ''; // ERROR
if ('prop2' in a) {
  a.prop2 = ''; // OK
}

为什么 TypeScript 让我声明这两个 props?我希望它在使用变量时一样严格。原始示例是一个 React 组件,它让我传递所有的 props。

顺便说一下,我不能添加 prop4,只能是 1、2 和 3。

英文:

This might be duplicated, but I cannot find an answer.

I have this type:

type A = {
    prop2: string;
    prop1: string;
} | {
    prop3: string;
    prop1: string;
}

As you can see, it has a shared prop and 2 different props.
But then I can use it like this:

const a: A = {
  prop1: '',
  prop2: '',
  prop3: '',
};

And it works!

But then I need to check that a has prop2 and prop3 to use it:

a.prop1 = '';
// @ts-expect-error
a.prop2 = ''; // ERROR
if ('prop2' in a) {
  a.prop2 = ''; // OK
}

Why does typescript let me declare both props? I would expect it to be as strict as when using the variable. The original example was a React component and it let me pass all props.

BTW, I cannot add a prop4, only 1, 2 and 3.

答案1

得分: 2

在2023年,这仍然是一个相关的问题,没有一个真正可接受的答案,不需要一些复杂的解决方法。这个jcalz提供的解决方案应该会对你有所帮助。

英文:

In 2023, it is still a relevant question that doesn't have a real acceptable answer that doesn't require some complex work around. This one by jcalz should help you.

huangapple
  • 本文由 发表于 2023年5月17日 16:28:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定