Require specific string as optional key in TypeScript interface

前端 未结 1 1226
心在旅途
心在旅途 2021-01-27 21:41

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

1条回答
  •  [愿得一人]
    2021-01-27 22:13

    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

    0 讨论(0)
提交回复
热议问题