I have a situation where I could have a number of optional, t-shirt size props added to an object. Is there a way to define a type and set it as the optional key\'s type in an i
A mapped type is not an interface. You can make it a type alias instead of an interface:
type TSizes = { [K in Size]?: string };
Note that I put the ?
in there which makes the properties optional, as you presumably want.
Once you have such a named type you can make an interface that extends it (since all of its property names are statically known):
interface ISizes extends TSizes { }
Or you can use the built-in Partial and Record utility types to do both at the same time:
interface Sizes extends Partial> { }
Then, Sizes
is an interface with optional property keys from Size
whose values are of type string
:
const s: Sizes = {
s: "foo",
m: "bar",
xxl: "bazzz"
}
Okay, hope that helps; good luck!
Playground link to code