How to strictly define a record in the return type

Viewed 155

Given the following type:

type Fn = () => Record<"A" | "B", boolean>;

I want to enforce the following typing:

const fn: Fn = () => ({
  A: true,
  B: true,

  // @ts-expect-error C should throw an error
  C: false
})

I was wondering if there's a way I could enforce typescript to accept only the exact return type and no more than that.

playground

1 Answers

I'm afraid it's impossible. The return type is covariance.

I checked typescript configs, there is no parameter to prevent return type covariance.

The only way I can find is declare the return value as its type before return.

type Ret = Record<"A" | "B", boolean>
type Fn = () => Ret;

const fn: Fn = () => {
  const ret: Ret = {
    A: true,
    B: true,
    C: false
  }
  return ret
}

Related