Home > Blockchain >  Infer generic for constant?
Infer generic for constant?

Time:10-02

Is it possible to infer a generic type for a constant in Typescript?

Specifically, I frequently-ish find myself writing identity functions just to enforce a generic type constraint on a value in typescript:

function inferGeneric<T>(t: MyTypeWithGeneric<T>) {
  return t;
}

const foo = inferGeneric(value);

For example: Typescript: force key and value to be of the same type?

Is it possible to do this without the function?

CodePudding user response:

There currently is no syntax for this to my knowledge. You can specify the type manually, but it can be more verbose.

Using the example from the other question:

type KeyValueSameDict<Keys extends string> = {
  [v in Keys]?: v;
};

function inferGeneric<T extends string>(t: KeyValueSameDict<T>) {
  return t;
}

const x = inferGeneric({ foo: 'foo', bar: 'bar' } as const);
const y = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<string>; // Loose
const z = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<"foo" | "bar">; // Same as x

// Something like this is probably what one would want here, but this is invalid:
const error = { foo: 'foo', bar: 'bar' } as KeyValueSameDict<infer T>;

CodePudding user response:

I'm not sure why you'd need to enforce the generic type, as the previous type should be compatible with anything you might want the generic type for.

Alas, what you want is currently not possible but there is an open issue and a PR in the TypeScript repository for this kind of type argument inference. I'm not entirely sure it covers your use case, but it should be a good starting point.

  • Related