I have some states e.g. ’active’ | ’disabled’ and I want to create CSS class for them:
component-name—-active etc.
I want to store this in obj:
const CLASS_MAP: <how to type this> = {
active: ’component-name—-active’,
disabled: ’component-name—-disabled’
}
I tried
type State = ’active’ | ’disabled’;
Record<State, `component-name—-${State}`>
But this allow me to do unexpected combination as active: component-name—-disabled
>Solution :
You can use TypeScript mapped types to map over your State keys and define the dependant values.
type State = `active` | `disabled`;
type StateMap = {[K in State]: `component-name—-${K}`};
This will give you the expected typechecking:
// [✅]
const s1: StateMap = {
active: "component-name—-active",
disabled: "component-name—-disabled",
};
const s2: StateMap = {
active: "component-name—-active",
// ❌ error: Property 'disabled' is missing in type '{ active: "component-name—-active"; }' but required in type 'StateMap'
};
const s3: StateMap = {
active: "component-name—-active",
disabled: "component-name—-active",
// ^^ ❌ error: Type '"component-name—-active"' is not assignable to type '"component-name—-disabled"'
};