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
}