How to use Optional chaining correctly in the unknown

Viewed 208

demo:

function getValue(data: unknown) {
  // return data?.value // error
  // or
  // use "value" in data to narrow the scope
  if (typeof data === 'object' && data && 'value' in data) {
    return data.value; // error
  }
  return '';
}

I don't want to use assertions data is similar to the data returned by a request

2 Answers

As Alex Chashin commented,typescript isn't able to infer types from the in operator very well at the moment.So maybe I need this function

function hasValue(it: unknown): it is ({ value: string }) {
    return typeof it === "object" && it !== null && "value" in it;
}

function hasStringValue(it: unknown): it is ({ value: string }) {
    return hasValue(it) && typeof it.value === "string";
}

Using type predicates

You can use generic types. For example:

type IData = {value: string}

function getValue<T extends IData>(data: T) {
  if (typeof data === 'object' && data && 'value' in data) {
    return data.value;
  }
  return '';
}
Related