The problem is that your array doesn't have micro
etc. when you assign it to the fontSizes
constant, but that constant's type requires it.
Object.assign
is often used to build up things like that (but keep reading, I work up to a third option which I think is probably best):
interface FontSizeAliases {
micro: number;
small: number;
default: number;
large: number;
}
const rawSizes = [12, 14, 16, 18, 22, 30, 40];
const fontSizes: number[] & FontSizeAliases = Object.assign(rawSizes, {
micro: rawSizes[0],
small: rawSizes[1],
default: rawSizes[2],
large: rawSizes[3],
});
Playground link
Another option is to build them up in a Partial<FontSizeAliases>
:
interface FontSizeAliases {
micro: number;
small: number;
default: number;
large: number;
}
const rawSizes: number[] & Partial<FontSizeAliases> = [12, 14, 16, 18, 22, 30, 40];
rawSizes.micro = rawSizes[0];
rawSizes.small = rawSizes[1];
rawSizes.default = rawSizes[2];
rawSizes.large = rawSizes[3];
const fontSizes = rawSizes as number[] & FontSizeAliases;
Playground link
In both of those, though, you have the issue that you could miss out one of the sizes (small
, for instance). To fix that, you can create the sizes separately with full typechecking, then combine them:
interface FontSizeAliases {
micro: number;
small: number;
default: number;
large: number;
}
const rawSizes = [12, 14, 16, 18, 22, 30, 40];
const sizeNames: FontSizeAliases = {
micro: rawSizes[0],
small: rawSizes[1],
default: rawSizes[2],
large: rawSizes[3],
};
const fontSizes = Object.assign([], rawSizes, sizeNames);
Playground link