Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Yes, TypeScript can perform narrowing using the NodeJS 'assert' function. The 'assert' function in NodeJS throws an error if the given condition is not true. This can be used to narrow down the type of a variable in TypeScript.

For example, consider the following code:

function printLength(str: string | number) {
  assert(typeof str === 'string');
  console.log(str.length);
}

Here, we pass a variable 'str' of type 'string | number' to the function 'printLength'. We use the 'assert' function to check if 'str' is a string. If the condition is true, then TypeScript narrows down the type of 'str' to 'string', which we can safely use to access the 'length' property.

If the 'assert' condition is not true, then an error will be thrown at runtime. Therefore, it is important to use the 'assert' function only when we are sure of the type of the variable.