Can I tell the interface to default the properties I don't supply to null? What would let me do this
No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support
Alternative
But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
And now when you create it you only need to provide a:
let x: IX = {
a: 'abc'
};
You can provide the values as needed:
x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
Answer from basarat on Stack OverflowCan I tell the interface to default the properties I don't supply to null? What would let me do this
No. You cannot provide default values for interfaces or type aliases as they are compile time only and default values need runtime support
Alternative
But values that are not specified default to undefined in JavaScript runtimes. So you can mark them as optional:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
And now when you create it you only need to provide a:
let x: IX = {
a: 'abc'
};
You can provide the values as needed:
x.a = 'xyz'
x.b = 123
x.c = new AnotherType()
You can't set default values in an interface, but you can accomplish what you want to do by using optional properties:
Simply change the interface to:
interface IX {
a: string,
b?: any,
c?: AnotherType
}
You can then do:
let x: IX = {
a: 'abc'
}
And use your init function to assign default values to x.b and x.c if those properies are not set.
Interface Default Values
Defaulting Unspecified Interface Properties to Null in TypeScript - Ask a Question - TestMu AI Community
Is there a way to have a default value for an object argument passed to a function?
Interface hint helper showing values that will be used defaultly ?
Interfaces, i think at least, is intended for example to define what properties and methods must be defined, their types and their eventual return values. It is then up to each class that implementes the interface to handle exactly how. The fictive Interface EmailSendingInterface does for example not dictate what api to call or how error handling should be implemented, but rather what methods and params other programs will use to utilize a class that implements the EmailSendingInterface.
Fictive class MailgunService might implememt the EmailSendingInterface interface, but the interface does not all care how the class sends emails (or if it even does). It just says hey, if they claim to conform to me they will have a SendEmail( sender: string, content: string) method. MailgunService might implement that method using mailgun api, but MockSender might implement that by console logging the parameters and returning an OK to the calling class.
Does it make it clearer why interfaces do not dictate values and implementations but only conformity rules for the actual implementating classes?
More on reddit.com