1

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?

1 Answer 1

2

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) => {} 
Sign up to request clarification or add additional context in comments.

3 Comments

Or you can do const sort = <T extends SortingType>(a: T, b: T) => {}
Your options is much easier to read, don't you mind if I add it to the answer?
sure, this is why I left a comment and upvoted your answer

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.