Home > front end >  Record type with automatic inference (e.g. `uknown`) from object literal
Record type with automatic inference (e.g. `uknown`) from object literal

Time:11-02

In typescript, I can either leave an object literal untyped so that type is automatically inferred, or I can specify a type (e.g. Record) so the type is enforced on the literal. -- (1)

I'd like to enforce Record<unknown, A> so that properties can be inferred from the literal (as an union type like "prop1" | "prop2" | "prop3") and values are type-checked against A.

I.e. I want to ask typescript to do half of what it does in each case in (1).

Is this possible? Record<unknown, A> complains instead of inferring type for unknown

TS2344: Type 'unknown' does not satisfy the constraint 'string | number | symbol'.   Type 'unknown' is not assignable to type 'symbol'.

See a minimal reproduction at this typescript playground link

CodePudding user response:

This would require partial type inference, which Typescript doesn't have yet.

One solution here would be to let TS infer the type and then verify the type of the record values, ie. something like

const obj = {
  prop1: 'foo',
  prop2: 42,
  prop3: true
}

function fun<Keys extends string>(input: Record<Keys, string | number>) {}

fun(obj) // error: boolean not an accepted value
  • Related