In TypeScript, we can make all the attributes of an interface optional by using the ?
symbol after the attribute name.
Here's an example:
index.ts70 chars6 lines
In this example, all three attributes are optional. We can create a User
object with any number of attributes, like this:
index.ts182 chars4 lines
Note that we can omit any of the attributes when creating a User
object.
If we want to require at least one attribute to be present, we can use a union type:
index.ts121 chars7 lines
In this example, we added an index signature to allow any string key to have a value of either a string
or a number
, and made all attributes optional. This allows us to require at least one of the attributes to be present, while still allowing any combination of attributes to be used.
gistlibby LogSnag