3 ms·
There are two solutions to this: 1. Take the type definition from the point of use, not the declaration. For example, if the object literal is being assigned
by nostrademons 9y ago
There are two solutions to this:
1. Take the type definition from the point of use, not the declaration. For example, if the object literal is being assigned to a variable, its type is the type of the variable. If it's being passed to a function, its type is (a subtype of) the type of the function parameter. If it's being returned, it's the return type of the current function. C/C++ and Kotlin do this, as does Scala (I think; I don't know the language well).
2. Use structural subtyping. In the type system, allow the possibility of expressing "HasField x && HasField y && HasField z". Then the type of the object literal is simply an anonymous type that includes those predicates. Ocaml and (I think) Go do this.
- bjourne 9y agoAh, you're right in case the syntax is for instantiating objects of existing classes/structs. My take was that the OP wanted the object literals to be able to create new types. In Javascript, var a = { x: 123, y: 456 } is meaningful without a prior class declaration.