On the test bench is TypeScript with "Interfaces are Open Ended". This is about following capability:
interface Point { x: number; y: number; } const myPoint: Point = { x: 1, y: 2 }; interface Point { z: number; }
If you compile this, you get:
error TS2322: Type '{ x: number; y: number; }' is not assignable to type 'Point'. Property 'z' is missing in type '{ x: number; y: number; }'.
It looks like TypeScript reads interfaces first.
It collects all members that it finds for Point
into just one interface (→ "open ended").
Then it reads the remaining code and finds that myPoint
violates the interface Point
contract,
because the property z
is not present.
In other words, it regards the duplicate definition of Point
as feature, not as bug.
The "premature" definition of myPoint
is regarded to be the bug.
I don't want to argue about bugs and features. Here is how I would fix this:
interface Point { x: number; y: number; } interface Point3D extends Point { z: number; } const myPoint: Point = { x: 1, y: 2 };
You should define any interface just once.
When you need more, extend it, but with a new descriptive name (like Point3D
).
That's the
OO way,
still the most popular and successful one.
Do not use language features that are useless.
But you should also read some TS docs
(see "Modifying native types")
and decide with your team if "open ends" are acceptable.
It is relieving to find out that such doesn't work when you have
this second interface Point
in another file.
Compiling following sources
gives you this error:
error TS2440: Import declaration conflicts with local declaration of 'Point'.
That's what I'd expected!
Freedom versus Safety
Why do programming languages provide freedom of expression? When it is about realizing technical issues for machines that do not forgive any mistake, freedom is not what we need. We need simple and precise expressions, built from culturally rooted terms. We need to be able to communicate about written source code, because very often the source code is the only existing business specification.
A single person can not cope with the complexity of today's applications, this must be done collectively. For that we need a common and easily understandable programming language. Freedom of expression makes communication about implemented functionality difficult up to impossible due to unreadable code.
So why are all these new languages full of freedom features that nobody needs? Because the language researchers need customers. They do everything to get you on their side. It's the free play of forces.
Keine Kommentare:
Kommentar veröffentlichen