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.ts85 chars4 linesThis 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.ts129 chars6 linesThis 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.ts385 chars11 linesIn 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