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:
- The correct type
const arr : ['foo','bar']= ['foo', 'bar'];
const arr = ['foo', 'bar'] as const;
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']