Andrei V
Andrei V

Reputation: 7508

Can I specify that an Array is not assignable to Record?

I have a member of type Record<number, MyType>. Currently, I can also assign an Array to it. I get it: an Array is an object (typeof [] => 'object') and the indices are the keys. Is it, however, possible to tell the compiler that I don't want to allow arrays to be passed to my variable(s) of type Record<int, WhateverType>?

const myRecord: Record<number, MyType> = []; // <= would like to have an error here

Upvotes: 4

Views: 568

Answers (1)

ford04
ford04

Reputation: 74680

A custom NumberRecord type can exclude an array by enforcing, that no length property exists (analogue to ArrayLike built-in declaration):

const t = {
  0: "foo",
  1: "bar"
}

const tArr = ["foo", "bar"]

type NumberRecord<T> = {
  length?: undefined; // make sure, no length property (array) exists
  [n: number]: T;
}

const myRecordReformed1: NumberRecord<string> = tArr; // error
const myRecordReformed2: NumberRecord<string> = t // works

Code sample

Upvotes: 5

Related Questions