Home > Software engineering >  Typescript issue when passing in specific strings
Typescript issue when passing in specific strings

Time:11-18

What is the issue with str below on line 15? I would have imagined the Typescript compiler can see that str will always be 'foo' or 'bar'

import { useEffect } from 'react'

type Type = {
  name: 'foo' | 'bar'
}

const Demo = () => {
  const update = ({ name }: Type) => console.log('logging: ', name)

  useEffect(() => {
    const arr = ['foo', 'bar']

    arr.forEach((str) => {
      update({
        name: str,
      })
    })
  }, [])

  return null
}

export default Demo

But the Typescript compiler says...

(property) name: "foo" | "bar"
Type 'string' is not assignable to type '"foo" | "bar"'.ts(2322)
file.tsx(4, 3): The expected type comes from property 'name' which is declared here on type 'Type'

CodePudding user response:

Your type is not narrowed enough.

const arr = ['foo', 'bar'] is considered of type string[].

Use one of the two below to get the right type:

  1. The correct type
const arr : ['foo','bar']= ['foo', 'bar'];
  1. const assertion
const arr = ['foo', 'bar'] as const;

Playground

CodePudding user response:

The inferred type of arr is just string[] because there is a single "best common type".

Add an explicit type annotation to make the type more specific:

    const arr: Type['name'][] = ['foo', 'bar']
  • Related