Home > Enterprise >  how to solve type script error is not assignable to parameter of type?
how to solve type script error is not assignable to parameter of type?

Time:01-12

any idea how to explain to type script that am passing the same required argument ? I am getting the following error (is not assignable to parameter of type '{ [key: string]: ""; } ) if you could please insert how would you declare types in case you would use this solution.

  const initialState = { name: '', gender: '', height: '', weight: '' };
  const [selected, setSelected] = useState<{ [key: string]: '' }>(initialState);

I tried this solution but seem like duplicate code

  type state = { [key: string]: '' };
  const initialState: state = { name: '', gender: '', measurements: '', height: '', weight: '' };
  const [selected, setSelected] = useState<state>(initialState);

CodePudding user response:

This is a better way to say the same thing:

const initialState = { name: '', gender: '', height: '', weight: '' };
const [selected, setSelected] = useState<typeof initialState>(initialState);

The problem with your approach is the way TypeScript is inferring the type and the way you are thinking it should.

You are thinking the inferred type looks like this:

{ [key: string]: '' }

Which means key can be any arbitrary string but the values can only be empty string i.e. ''.

While the way typescript is inferring it, (and more commonly this is what one wants) is as follows

{
    name: string;
    gender: string;
    height: string;
    weight: string;
}

So, when you say,

const [selected, setSelected] = useState<{ [key: string]: '' }>(initialState);

You are assigning a wider type to a narrower type. TypeScript is thinking the initialState can have string type as values while you are implying that it cannot have anything other than empty string. Hence the error.

The another problem with your { [key: string]: '' } typing is you are allowing keys to be any string. Which is fine if you want any arbitrary object as state. (you could have used Record<string, string>). But in majority of cases, you'd want stricter typing. So, you should use this instead:

<typeof initialState>

But hey, since TypeScript is doing the hard work for you, this should be just fine:

const [selected, setSelected] = useState(initialState);
  •  Tags:  
  • Related