Home > Enterprise >  TypeScript: Two variables with unknown type, but the same
TypeScript: Two variables with unknown type, but the same

Time:12-22

Imagine I have a sorting function with

type sortingType = 
    string | number | boolean | { [key: string]: unknown }; // basically unknown

const mySortFun = (a: sortingType, b: sortingType) => { /* do the thing */ };

But I know, that if a is type X, then b is also type X. How can I tell typeScript?

CodePudding user response:

You need to somehow bind a and b variables together, like this:

type SortingType =
    string | number | boolean | { [key: string]: unknown }; // basically unknown

type Func = <T extends SortingType>(a: T, b: T) => void;

const mySortFun: Func = (a, b) => { /* do the thing */ };
mySortFun(1, 2)

I introduced new type type Func = <T extends SortingType>(a: T, b: T) => void; where a and b have the same generic type T. Now they are coupled together.

If you don't want to have extra type, the option from @captain-yossarian will be really useful:

const sort = <T extends SortingType>(a: T, b: T) => {} 
  • Related