Trusting TypeScript Array Types is Dangerous
I ran into an interesting problem today where the types from an array were not what I expected. Having done a bunch of Rust code (I’m not saying I’m good at it yet)– I was expecting something a little different:
const examples = ["a", "b", "c"];
const value = examples[123];
const exampleFunc = (v: string): number => {
return v.length;
};
exampleFunc(value);
So what type to you expect value to be?
Coming from recent work with stricter types, I was expecting this to be string | undefined – just in case you got your indexing wrong, but it turns out it’s just a string! I understand that TypeScript can only perform compile-time checking, resulting in not being able to detect if an index is in-bounds or not; but even with strict enabled, I’m not seeing an option which lets this detect any kind of undefined outcome due to an index not being expected.
Similarly, the other day I provided some feedback to another engineer that the Record<T, U> type is great for representing a mapping, but can become a footgun if you do a simple: Record<string, string>:
const exampleMap: Record<string, string> = {
key1: "value1",
key2: "value2",
key3: "value3",
};
const value = exampleMap.key4;
Innocent enough, but value is again a string.. you would need to use Record<string, string | undefined> to get the safety you need.