Search code examples
node.jstypescriptvalidationtypestypeerror

Type checking in separate function not working in typescript


I'm validating type of parameter in separate function but still it is giving the following Error-

Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'.

The code is like this-

function paramValidator(param?: string){
  if(param===undefined){
    throw new Error('parameter missing');
  }
}
function xyz(a: string){
  console.log(a);
}

function abc(a?: string){
  try{
    paramValidator(a);
    // Working Fine
    // if(a===undefined){
    //   throw new Error('parameter missing');
    // }
    xyz(a);  //This line is throwing error
  }
  catch(e){
    console.log('Error');
  }
  
}

I want to put validation logics in a separate function for cleaner code. How to enforce that the parameter is defined after validation?


Solution

  • If you are using Typescript 3.7+, use you use assertion functions. The change is minimal; you simply add an asserts condition to your method signature:

    function paramValidator(param?: string): asserts params is string {
    

    Any time after you have called this function, Typescript will recognise that the value of param should be string, and you won't get the error.

    Playground link