Description
TypeScript Version: 3.5.1
Search Terms:
Partial, keyof, typeof, Record, nested object
As a part of a design system I'm making, I want to create a list of sizes that a component may define for itself.
Say I have a list of small
, medium
, large
.
Now I want to define an object mapping one the above sizes to the actual size like
const sizes = ['small', 'medium', 'large'] as const;
const buttonSize = {
small: '20px',
large: '40px'
}
I want that object to enforce using keys from the list of sizes, and then to enforce the consumer of the property to pass only defined sizes (that is small
and large
).
The best I came up with is to say that buttonSize
is an object built from some of sizes
.
This however could not limit the option for the consumer (see below snippet).
Seems like trying to get the keys of the buttonSize
was just delegating you to size
.
Either there is an issue here, or I completely misunderstood this usage of the types.
Code
import React, { FunctionComponent } from 'react';
const sizes = ['small', 'medium', 'large'] as const;
const buttonSize: Partial<Record<typeof sizes[number], any>> = {
small: '20px',
large: '20px'
} as const;
interface IButtonProps {
size: keyof typeof buttonSize;
}
const Button: FunctionComponent<IButtonProps> = () => ();
<Button size={...} />;
Expected behavior:
Only small | large
should be allowed in size
property (not allowing medium
)
Actual behavior:
Every one of the sizes is allowed (small | medium | large
).
Related Issues:
This might relate