是否可以键入 checkVar 函数以避免出现错误?
TS2322: Type string | undefined is not assignable to type string
?
// TestComponent accepts a string parameter fooProp.
function TestComponent({ fooProp }: { fooProp: string }) {
// ... some actions with fooProp
return null;
}
// foo variable can be string or undefined.
const foo = Math.random() > 0.5 ? 'foo value' : undefined;
// Function checks presence of variable
const checkVar = (x: string | undefined): boolean => !!x;
// If bar is undefined then checkVar(bar) is false
if (checkVar(foo)) {
return <TestComponent fooProp={foo} />; // TS2322: Type string | undefined is not assignable to type string
}
这是简化的代码,可能看起来很人为。我知道您可以使用
type assertion
或 non-null assertion
。这个问题不是关于解决特定问题,而是更多关于 TypeScript 的功能。
如果需要自定义函数,则需要使用类型谓词
const checkVar = (x: string | undefined): x is string => !!x;