Sobes.tech
Middle

How to type a function that takes unknown and returns a specific type so that TypeScript always considers the return value to be that type?

sobes.tech AI

Answer from AI

To type a function in TypeScript that accepts unknown and returns a specific type, and for TypeScript to always consider the return value as that type, you can use a type assertion (as) or a user-defined type guard.

For example, if a function converts unknown to type MyType and we are confident in the correctness of the conversion:

type MyType = { name: string; age: number };

function parseToMyType(value: unknown): MyType {
  // checks can be added here if needed
  return value as MyType;
}

const result = parseToMyType(someUnknownValue);
// TypeScript now considers result as type MyType

If a more strict check is needed, you can implement a predicate function:

function isMyType(value: unknown): value is MyType {
  return typeof value === 'object' && value !== null &&
    'name' in value && typeof (value as any).name === 'string' &&
    'age' in value && typeof (value as any).age === 'number';
}

function parseToMyType(value: unknown): MyType {
  if (isMyType(value)) {
    return value;
  }
  throw new Error('Invalid type');
}

This way, TypeScript is guaranteed to know that the return value is MyType.

How to type a function that takes unknown and returns… - sobes.tech