【问题标题】:Typescript property only allowed if another property exists仅当存在另一个属性时才允许使用 Typescript 属性
【发布时间】:2020-11-07 08:30:20
【问题描述】:

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

我试图这样做,但它返回错误 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 };
};

有什么解决办法吗?

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    我知道的唯一方法是User defined Type Guard,我喜欢将它与Union Types结合起来

    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
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 2016-09-15
      相关资源
      最近更新 更多