function that returns unknown input object as type of interface if the object parameter matches type literal of interface. in typescript

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.ts
interface Person {
    name: string;
    age: number;
}

function isPerson(obj: unknown): obj is Person {
    return (typeof obj === 'object') &&
           (obj !== null) &&
           ('name' in obj) && (typeof (obj as Person).name === 'string') &&
           ('age' in obj) && (typeof (obj as Person).age === 'number');
}

function getPerson<T extends Person>(obj: unknown): T | undefined {
    if (isPerson(obj)) {
        return obj as T; // obj is now type T
    }
    return undefined;
}
495 chars
19 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.ts
const personObj = { name: 'John', age: 30 };
const person = getPerson<Person>(personObj); // person is typed as Person

const animalObj = { breed: 'Labrador', weight: 50 };
const animal = getPerson<Person>(animalObj); // animal is undefined
241 chars
6 lines

gistlibby LogSnag