我是TypeScript的新手,不确定是不是Bug,并且设置了错误。因此,我的React功能组件中包含以下代码行:
const [user, setUser] = useState<{email: string}|null>(null);
当我将鼠标悬停在user
上时,我会看到const user: {email: string;}
,而我期望是const user: {email: string;}|null
。在以下几行中使用user.email
时,看不到任何警告,例如“对象可能为'null'。”。
这是预期的行为吗?如果是这样,键入可为空的状态变量的正确方法是什么?
我正在使用TypeScript版本3.9.7,这是我的tsconfig.json
:
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": ["node_modules", ".next", "out"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "**/*.js"]
}
答案 0 :(得分:1)
启用“ strict”编译器选项将启用所有严格的类型检查选项,包括“ strictNullChecks”。没有启用它不会给您“对象可能为'null'。”警告。
您可以通过将选项添加到tsconfig.json来显式启用此功能。
"strictNullChecks": true