Home > Back-end >  Typescript type error is not getting fixed by type narrowing
Typescript type error is not getting fixed by type narrowing

Time:11-07

I have a type called Level and its numbers are between 1 and 6 (both 1 and 6 included). I have another list of number which is between 1 and 8 i have a function which accepts Level I tried to narrow the type but didn't got fixed:

type Level = 1 | 2 | 3 | 4 | 5 | 6;

onSelect={(level: number) => {
  // level is between number 1 to 8 but the setHeading function bellow accepts an object with a level key that it's type is Level 
  if ([1, 2, 3, 4, 5, 6].includes(level)) {
    editor.commands.setHeading({
      level,
    });
  } else if (level === 7) {
    editor.commands.setParagraph();
  }
}}

There shouldn't be any errors because i narrowed the level to Level but in VS Code i get an error which says:

Type 'number' is not assignable to type 'Level'.ts(2322)
heading.d.ts(16, 17): The expected type comes from property 'level' which is declared here on type '{ level: Level; }'

I tried to narrow the level and get everything working but i still get the same error.

CodePudding user response:

The .includes method was written without any type predicate. This means it has no narrowing capabilities and leaves the types of its inputs untouched.

You would have to write your own type guard which wrappes the includes logic.

const isLevel = (level: number): level is Level => {
    return [1, 2, 3, 4, 5, 6].includes(level)
}

const onSelect =(level: number) => {
  if (isLevel(level)) {
    setHeading({
      level,
    });
  } 
}

Playground

  • Related