0

I have the following code where I want to pass data to an if block with 2 different types that are tackled in if block how to make type script know that the (selected object) is customary and in the other scenario custom plane since I am passing 2 different types and I don't want to do 2 different actionGuard functions but one that can handle both cases at once, in other words, the selected object is erroring out in the if condition saying that selected could be this or this a both are different in keys and values and without having to use casting.

import { CustomCar } from '../app/carSlice';
import { CustomPlane } from '../app/planeSlice';


export const actionGuard = (
  selected: CustomCar | CustomPlane 
  check: CustomCar[] | CustomPlane[] 
  term: string,
  dispatch: any,
  SetSnackBarMsg: any,
  action: string
) => {
  if (term === 'CustomCar' ) {
    if (array.includes((selected as CustomCar){
     // some logic 
    }
   
    if (term === 'CustomPlane') {
    if (array.includes((selected as CustomPlane ){
    // some logic 
    }
};

1 Answer 1

1

While you can assert that the value being passed into .includes is the same type as the array item - as you're doing - you could also assert that the array itself is unknown[], so that you can pass anything into its .includes.

if ((array as unknown[]).includes((selected){
  // some logic 
}

Unfortunately, some sort of type assertion (with as) is required, due to an odd TypeScript design decision with .includes.

Sign up to request clarification or add additional context in comments.

2 Comments

So some times there is no escape from assertion.
Usually you can avoid assertions when functions are typed well. Still, .includes isn't typed well IMO (see that linked github thread).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.