问题描述
const props: { id: number,name?: string} = { id: 1 }; // not defining the `name`
const { id,name } = props; // here the `const name` becomes undefined forever and even if I use the defaultProps pattern of React,Typescript still shows warnings for potential undefined
有没有办法在销毁对象时使用无效合并? 我不能使用这个(由于团队定义的 ESlint 规则):
const name = props.name ?? 'placeholder name';
解决方法
如果 name
未定义,您可以指定默认值,而不使用可选链:
const { id,name = 'placeholder name' } = props;