在 TypeScript 中将 string prop 传递给组件时如何避免显式未定义检查?

问题描述 投票:0回答:1

是否可以键入 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 的功能。

typescript
1个回答
1
投票

如果需要自定义函数,则需要使用类型谓词

const checkVar = (x: string | undefined): x is string => !!x;  
© www.soinside.com 2019 - 2024. All rights reserved.