return type t if param matches value in typescript

One way to achieve this goal in Typescript is through the use of type-guards and conditional types.

A type-guard is a function that returns a boolean value and can be used to refine the type of an object. In our case, we want to check if a parameter matches a certain value.

Here's an example of a type-guard:

index.ts
function isMatching<T>(param: T, value: T): param is T {
  return param === value;
}
85 chars
4 lines

This function takes two parameters: param which is the value we want to check and value which is the value we want to compare it to. The return type is a type predicate, which means it's a boolean value that tells Typescript to refine the type of param.

Now, we can use this type-guard in a function that returns a type T if param matches value:

index.ts
function returnMatching<T>(param: any, value: T): T | undefined {
  if (isMatching(param, value)) {
    return param as T;
  }
}
129 chars
6 lines

This function takes a param of type any (since we don't know the type of param upfront) and a value of type T. It uses the isMatching type-guard to check if param matches value. If so, it returns param as type T. If not, it returns undefined.

Here's an example of how to use this function:

index.ts
interface Person {
  name: string;
  age: number;
}

const person: Person = { name: 'Alice', age: 30 };

const matchingName = returnMatching(person, 'Alice'); // matchingName is of type string | undefined
const matchingAge = returnMatching(person, 30); // matchingAge is of type number | undefined
const nonMatching = returnMatching(person, false); // nonMatching is of type undefined
385 chars
11 lines

In this example, we have an interface Person with two properties: name of type string and age of type number. We have an object person of type Person. We call returnMatching with person as the first parameter and a value of type string, number, and boolean respectively as the second parameter.

The first call to returnMatching returns a type of string | undefined because person has a name property with the value 'Alice'. The second call returns a type of number | undefined because person has an age property with the value 30. The third call returns undefined because person doesn't have a property with the value false.

gistlibby LogSnag