Reputation: 7508
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
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
Upvotes: 5