You can define a function that has a generic type variable that extends an interface. The function then takes an argument of type unknown
. You can use a type guard to check if the argument matches the type literal of the interface. If it does, the function returns the argument as the type of the interface.
Here's an example:
index.ts495 chars19 lines
In this example, isPerson
is a type guard that checks if the input object matches the type literal of the Person
interface. The getPerson
function takes an input object of type unknown
and returns it as type T
, which extends the Person
interface. If the input object does not match the Person
interface, the function returns undefined
.
You can call the getPerson
function with an input object, and it will return the typed object if it matches the Person
interface:
index.ts241 chars6 lines
gistlibby LogSnag