Given an interface
interface IAmOptional {
optional? : string,
optional2?: string
forced: string
}
Is there a way to covert, extend or similar IAmOptional
in a way that this implementation fails?
class someClass {
thisShouldHaveAllKeys : IAmOptional = { // Forced<IAmOptional> ??
forced: 'i am forced'
} // Here I want an error like 'thisShouldHaveAllKeys does not have optional and optional2'
}
The declaration of the interface is a place to make some properties optional. You can achieve that with a question mark next to the properties names. In the above example, the pet is an optional property.
In TypeScript, interfaces represent the shape of an object. They support many different features like optional parameters but unfortunately do not support setting up default values. However, you can still set up a TypeScript interface default value by using a workaround.
Use the Partial utility type to make all of the properties in a type optional, e.g. const emp: Partial<Employee> = {}; . The Partial utility type constructs a new type with all properties of the provided type set to optional. Copied!
Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.
Yes, starting with TypeScript 2.8 there is a way to programmatically remove the optional modifier from properties using the -?
syntax with mapped types:
type Required<T> = { [K in keyof T]-?: T[K] }
This gives you the behavior your want:
class someClass {
thisShouldHaveAllKeys: Required<IAmOptional> = { // error!
//~~~~~~~~~~~~~~~~~~~~~ <-- missing properties optional1, optional2
forced: 'i am forced'
}
}
In fact, this Required
type alias is so useful that it's predefined for you in the standard library. So you can just use it without defining it.
Hope that helps. Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With