Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/43.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 仅当存在其他属性时才允许使用Typescript属性_Javascript_Node.js_Typescript - Fatal编程技术网

Javascript 仅当存在其他属性时才允许使用Typescript属性

Javascript 仅当存在其他属性时才允许使用Typescript属性,javascript,node.js,typescript,Javascript,Node.js,Typescript,假设我有一个函数,在这个函数中,我只想在存在另一个属性的情况下允许一个属性 我尝试这样做,但返回时出错类型“A”上不存在属性“c”。 type A = { a?: string; } & ({ b: string; c?: string } | { b?: string }); const sad = (props: A) => { const { a, b } = props; const { c } = props; // Property 'c' does

假设我有一个函数,在这个函数中,我只想在存在另一个属性的情况下允许一个属性

我尝试这样做,但返回时出错
类型“A”上不存在属性“c”。

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 };
};
有什么解决方法吗?

我知道的唯一方法是,我喜欢将它与

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

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
}