4 ms·
A simple TypeScript example: interface DuckTypedObject { quack: true bark?: false eyes: 'beady' } This will require that any object
by crooked-v 7y ago
A simple TypeScript example:
interface DuckTypedObject {
quack: true
bark?: false
eyes: 'beady'
}
This will require that any object used as a DuckTypedObject must have the `quack` and `eyes` properties and may optionally have a `bark` of `false`, but doesn't otherwise prescribe what the object actually has to be.
- Scarbutt 7y agoThis is the best part of TS IMO (structural typing).
- ledauphin 7y agoagreed 100%. structural, statically-checkable typing of objects is the best thing to happen for reusable and testable code in my programming lifetime.
- deleted 7y ago[deleted]
- uk_programmer 7y agoSorry to be pedantic but that isn't quite right. I do use the same technique myself quite a lot with the options pattern. However it is worth keeping the following in mind. The compiler will check that in your code that these properties are present and assigned correctly. However at runtime nothing is guaranteed especially when dealing with the DOM. One of the things that I don't like about TypeScript (I have written a fair bit of it) is that you believe you have type safety when it is really type hinting.
- crooked-v 7y agoValidation functions are pretty easy to write, as long as your data is being handled in a predictable way.
- uk_programmer 7y agoYes. However you can for example do the following in typescript: function someFunction(obj?:DuckType) { //Snip other logic someOtherFunction(obj); } function someOtherFunction(obj:DuckType) { } The type checker catch that. So you still have to do: function someFunction(obj?:DuckType) { obj = obj || { /* set some object properties */ //Snip other logic someOtherFunction(obj); } function someOtherFunction(obj:DuckType) { } I have found plenty of examples where people haven't set a default value because the compiler hasn't flagged anything wrong with the code and you get an uncaught reference error.
- tome 7y agoHuh, shouldn't the things on the right hand side of the colons be types not values?