Search code examples
typescriptgenericscastingconstantsnarrowing

Generic Object Param as Its Literal


I have a simple function that accepts a generic object. The return type should be the same as that object, but narrowed similar to how as const assertions work.

for instance. The following should have a return type of { a: "first"; b: "second" } and not { a: string; b: string }:

myFn({ a: "first", b: "second" });

Is there a mechanism by which we can instruct the type-checker that the return type of myFn is its 1st argument type, narrowed?


Solution

  • The return type should be the same as that object, but narrowed similar to how as const assertions work.

    You can achieve this by passing in the type as a type parameter to the function.

    function myFn<T>(args): T {
      // do stuff
      return null;
    }
    
    const a = myFn<{ a: "first"; b: "second" }>(args);
    

    enter image description here

    type MyObj = { a: "first", b: "second" }
    const a = myFn<MyObj>(args);
    

    Unfortunately the object needs to be fully defined at compile time as types are not available at runtime.

    Old answer (misinterpreted)

    If you want the return type to be the same as the argument type. Then you can use the generic type parameter.

    function MyFunction<T>(argument1: T, anotherArg: number): T {
      // do stuff
    }
    
    // result will be of type User
    const result = MyFunction<User>(user, 9);
    

    In some cases, you can just do.

    // user must be defined as type User above somewhere
    const result = MyFunction(user, 9);