David
David

Reputation: 7456

TypeScript: how to have return type be the type of a parameter?

I have something like this:

const shiftObjValues = (obj: Object, shift: number): Object => { ... }

I have an interface like such:

interface Range {
  start: number;
  end: number;
}

Now, this is an Object and when it is passed into the function I want the return type to be Range.

I don’t want to have to continue doing as Range when using the function but I want it to maintain flexible in being able to take in any Object.

Edit: I originally wanted this without generics but didn’t understand generics were usable in a different way (as accepted answer shows)

Upvotes: 0

Views: 127

Answers (1)

Aaron Beall
Aaron Beall

Reputation: 52133

Yes, you want to use a generic (aka type argument) to preserve the incoming type. You can use a type constraint to ensure it is an object.

const shiftObjValues = <T extends object>(obj: T, shift: number): T => { /* ... */ }

Note I used object not Object, as Object is almost anything in JS, including strings and numbers, which I don't think is what you meant.

Also note that you don't have to explicitly pass the type argument, meaning this works fine:

let range: Range = { start: 0, end: 1 };
let shifted = shiftObjValues(range, 1);
// `shifted` is inferred as type `Range`

Upvotes: 3

Related Questions