你能破坏一个对象并为潜在的未定义常量进行无效合并吗?

问题描述

我使用 React,所以我有一个 props 对象,例如:

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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...