V
V
Vlad Tokarev2019-07-29 13:49:51
typescript
Vlad Tokarev, 2019-07-29 13:49:51

How to use null check in TypeScript in function instead of if?

It is easier to explain the question with a simple example

const isNotEmptyString = (str: string|null): boolean => {
  if (!str) {
    return false;
  }
  return !!str.length;
};

const getStringLength = (str: string|null): number => {
  if (!isNotEmptyString(str)) {
    return 0;
  }
  return str.length; // Qualifier of 'length' is possibly null
};

In "isNotEmptyString()" I check the parameter for "null" - if it is "null", the function will return ``false``.
In "getStringLength()" I call "isNotEmptyString()" and if "isNotEmptyString()" returns true, then it is logical that the passed parameter "str" ​​will not be "null". But TypeScript still requires a check for "null" in the "getStringLength()" method.
Is there any way to avoid the extra "if (str)" in "getStringLength()"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
forspamonly2, 2019-08-03
@Vadiok

can. it's called type-predicate

const isNotEmptyString = (str: string|null): str is string => { ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question