'typescript not recognising type for the tupple returned
Below code throws an error when the tuppleFunc is used in the error field for the payload.
interface FormItemPayload {
value: string;
error: boolean;
errorMsg: string;
}
const tuppleFunc = (inputA: string, inputB: string) => {
const somecondition = inputA === inputB;
return somecondition ? [false, 'error'] : [true, ''];
};
const payload: FormItemPayload = {
value: 'bla bla',
errorMsg: '',
error: tuppleFunc('a', 'a').at(0),
};
the function will always return a type of array as below whose type is (boolean|string)[]
[false, 'error string dummy']
// or
[false, 'error string dummy']
for reference attaching the typescript logs
Type 'string | boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.ts(2322)
index.tsx(41, 5): The expected type comes from property 'error' which is declared here on type 'FormItemPayload'
My question
- function clearly says that the first element will be on type boolean and second to be string.
- at index 0 it will always be boolean so why is typescript complaining that it can be undefined?
- my doubt is around the type
(boolean|string)[]
but i dont understand it very well. - i understand that it can be an array with boolean and string but unsure how to say at what index will it be
- i also tried with giving the type
[boolean,string]
but no luck
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|