Skip to content

Instantly share code, notes, and snippets.

@serslon
Created February 22, 2022 14:34
Show Gist options
  • Select an option

  • Save serslon/bd9d8e733e65e6c52fa8ba074e95173c to your computer and use it in GitHub Desktop.

Select an option

Save serslon/bd9d8e733e65e6c52fa8ba074e95173c to your computer and use it in GitHub Desktop.
How to check variable is one of the types?

This function resolves the problem with different values in a function or class.

Example: We have a function with different parameters and descriptions like:

interface MyExample1 {
 count: number;
 cost: number;
}

interface IMyExample2{
 items: string[];
 cost: number
}

// The simple function returned 

function Sum(data: MyExample1|IMyExample2) {
 return cost * (isItType<MyExample1>(data, "count") ? count : items.lenght);
}

The function isItType help understand with the exact interface we are using at this time.

export function isItType<T extends unknown>(value: any, field: string): value is T {
return field in value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment