![](/img/trans.png)
[英]Why is TypeScript showing “Cannot invoke an object which is possibly 'undefined'.ts(2722)” error after optional chaining operator?
[英]React typescript props not showing as possibly defined, even when I use '?' optional operator and '| undefined'
我的 linter 似乎已经停止标记传递给我的 React 组件的可能未定义的属性。 例如:
interface BooleanTypeObject {
prop1: true
}
interface MyComponentProps {
disabledObject?: BooleanTypeObject | undefined;
}
export function MyComponent({
disabledObject
}: MyComponentProps): ReactElement {
...
}
如果我尝试在我的组件中访问prop1
,我不会收到任何 linter 错误。 但是如果disabledObject
是undefined
,我会在编译代码时这样做。 我确定当我使用?
运算符,或用| undefined
指定 | undefined
。
我本来希望看到(parameter) disabledObject: BooleanTeeTypeObj | undefined
此处(parameter) disabledObject: BooleanTeeTypeObj | undefined
。
我所有的其他 linting 似乎仍然适用于 typescript。 谁能想到发生了什么?
tsconfig.json
{
"compilerOptions": {
"target": "ES2018",
"module": "commonjs",
"checkJs": false,
"jsx": "react",
"sourceMap": true,
"strict": false,
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
这是因为您有strictNullChecks: false
。 当它设置为 false typescript 忽略null
和undefined
完全和BooleanTypeObject | undefined
BooleanTypeObject | undefined
等价于BooleanTypeObject
。 如果您希望 typescript 显示错误,则需要将其设置为strictNullChecks: true
https://www.typescriptlang.org/tsconfig#strictNullChecks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.