首页 > 解决方案 > React - Typescript interfaces - errors when get props from union types

问题描述

I use react with typescript.

I want to require only one parameter be accepted from prop3 | prop4. I use a union type like this:

interface General {
  prop1?: boolean
  prop2?: boolean
}

interface Option1 extends General {
  prop3: boolean
}

interface Option2 extends General {
  prop4: boolean
}

type Option1orOtion2 = Option1 | Option2

If I get prop3 I don't want that prop4 will be accepted.

When I do that I get errors about those values. What I do worng?

export default function({
  prop1 = true,
  prop2 = true,
  prop3 = true, // error: Property 'prop3' does not exist on type 'Option1orOtion2'
  prop4 = true  // error: Property 'prop4' does not exist on type 'Option1orOtion2'
}: Option1orOtion2) {
  return <></>
}

EDIT: When I do that with variable there aren't errors, but let me to pass prop3 and also prop4, and I want to get a error about it (Option1 or Option2 ).

var data: Option1orOtion2 = {prop3: false, prop4: false}

Any suggestion?

Thanks in advance!

标签: javascriptreactjstypescriptreact-functional-component

解决方案


这类问题可以使用函数原型来解决,函数原型用于在 ts 中进行重载。

对于您的情况,我有 2 个解决方案

interface General {
    prop1?: boolean
    prop2?: boolean
}
  
interface Option1 extends General {
    prop3: boolean
}
  
interface Option2 extends General {
    prop4: boolean
}

使用函数原型来限制可以给出的参数类型。(我假设返回类型为字符串,只需将其更改为您想要的)

export default function test(param: Option1): string;
export default function test(param: Option2): string;

第一个解决方案:使用联合

export default function test({
    prop1 = true,
    prop2 = true
}: Option1 | Option2): string {
    return ''
}

对于这个解决方案,我还没有找到任何为 prop3 和 prop4 创建默认值的解决方案。

第二种解决方案

interface Param extends General {
    prop3?: boolean;
    prop4?: boolean;
}
export default function test({
    prop1 = true,
    prop2 = true,
    prop3 = true,
    prop4 = true
}: Param): string {
    return ''
}

我制作了另一个接口,其中 prop3 和 prop4 设置为可选属性。

由于函数原型,如果我像下面这样调用它,它会导致错误

test({prop4: true, prop3: true}) // error

推荐阅读