How to avoid explicit undefined check when passing string prop to component in TypeScript?

  Kiến thức lập trình

Is it possible to type the checkVar function so that an error does not occur?
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  
}

This is simplified code that may look artificial. I know that you can use type assertion or non-null assertion. This question is less about solving a specific problem and more about the capabilities of TypeScript.

If you need a custom function, you need to use a type predicate

const checkVar = (x: string | undefined): x is string => !!x;  

All you need is a type predicate in order to check if foo is not null.

function TestComponent({ fooProp }: { fooProp: string }) {
  return null;
}

const foo = Math.random() > 0.5 ? "foo value" : undefined;

function IsDefined(value: string | undefined): value is string {
  return value !== undefined;
}

function Parent() {
  if (IsDefined(foo)) {
    return <TestComponent fooProp={foo} />; 
  }
  
  return null;
}

TypeScript Playground

LEAVE A COMMENT