Since Record<Intent, Color>
is a named object type whose keys are statically known at compile time, you can have an interface
extend it:
interface IntentColors extends Record<Intent, Color> {
primary: '#fff' | 'white';
secondary: '#000' | 'black';
error: '#ff0000' | 'pink';
}
This is concise, and it will warn if you try to narrow one of the existing properties with a bad value type, like:
interface BadIntentColors extends Record<Intent, Color> { // error!
primary: '#fff' | 'white';
secondary: number; // oops
error: '#ff0000' | 'pink';
}
If you don't mention primary
, secondary
, or error
in the declaration, they will stay string
, because that's how interface extension works (interface Bar extends Foo {}
means that Bar
has the same properties as Foo
). This could be a problem if you misspell a property, since the compiler will just add it as a new property, without warning:
interface UncaughtIntentColors extends Record<Intent, Color> {
primairy: '#fff' | 'white';
secondery: '#000' | 'black';
erorr: '#ff0000' | 'pink';
} // no errors
It's up to you to decide whether the conciseness of interface extension is worth this possible stumbling point.
A different approach is to add a helper type alias you can use to verify your constraint:
type Extends<T, U extends T> = void;
The Extends
type doesn't evaluate to anything interesting (it's always void
), but if you write Extends<A, B>
then there will be an error if B
is not assignable to A
.
So you can first define IntentColors
without mentioning Record<Intent, Color>
:
type IntentColors = {
primary: '#fff' | 'white';
secondary: '#000' | 'black';
error: '#ff0000' | 'pink';
}
and then check it using Extends
:
type TestIntentColors = Extends<Record<Intent, Color>, IntentColors>; // no error
If you make any kind of mistake:
type BadIntentColors = {
primary: '#fff' | 'white';
secondery: '#000' | 'black'; // oops
error: '#ff0000' | 'pink';
}
It should be caught:
type TestBadIntentColors = Extends<Record<Intent, Color>, BadIntentColors>; // error!
// -----------------------------------------------------> ~~~~~~~~~~~~~~~
// Property 'secondary' is missing in type 'BadIntentColors'
// but required in type 'Record<Intent, string>'.
This might be closer to the behavior you're looking for, but again it's up to you to decide if this behavior is worth the verbosity of adding a helper type alias and an separate "check" line of code.
Okay, hope one of those helps. Good luck!
Playground link to code