仅当存在另一个属性时才允许使用 Typescript 属性

med*_*123 8 javascript node.js typescript

假设我有一个函数,我只想在存在另一个属性时才允许使用某个属性。

我尝试这样做,但它返回错误 Property 'c' does not exist on type 'A'.

type A = {
  a?: string;
} & ({ b: string; c?: string } | { b?: string });

const sad = (props: A) => {
  const { a, b } = props;

  const { c } = props;  // Property 'c' does not exist on type 'A'.

  return { a, b };
};
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?

Ant*_*ond 5

我知道的唯一方法是用户定义的类型防护,我喜欢将它与联合类型结合起来

interface CommonProps {
    a?: string
    b?: string
}

interface SimpleProps extends CommonProps {
    kind: "simple"
}

interface ComplexProps extends CommonProps {
    kind: "complex"
    c?: string
}


type Props = SimpleProps | ComplexProps

function isComplex(arg: Props): arg is ComplexProps {
    return arg && arg.kind === 'complex'
}

const sad = (props: Props): any => {
    if (isComplex(props)) {
        const {a, b, c} = props
        // do something
        // return something
    }
    const { a, b } = props
    // do something
    // return something
}
Run Code Online (Sandbox Code Playgroud)

简而言之,我为每种可能的属性组合创建了一个接口。然后我将它们联合到Props类型下,并在我的函数中使用user defined guards来访问属性。