4 ms·
One of the very useful things Typescript has for a dynamic-language-turned-static is smart casts, union types and dependent types union types. Things like these
by dtech 7y ago
One of the very useful things Typescript has for a dynamic-language-turned-static is smart casts, union types and dependent types union types.
Things like these are possible:
type Animal =
{
type: "Dog"
dogtag: string
name: string
} | {
type: "Cat"
name: string
allowedOutside: boolean
}
function f(a: Animal) {
console.log(a.name) // always allowed
console.log(a.dogtag) // compile error
if(a.type === "Dog") {
console.log(a.dogtag) // Allowed
}
}
I believe Typescript is fairly unique in this capability.
- mijamo 7y agoYou can do that in Python as well though. from typing import Union class Dog: dogtag: str name: str class Cat: name: str allowedOutside: bool Animal = Union[Cat, Dog] def do(a: Animal): print(a.name) # Always allowed print(a.dogtag) # MYPY error if isinstance(a, Dog): print(a.dogtag) # MYPY allows
- sametmax 7y agoAnd you can even do that with dict in the most recent version of mypy. But the fact you have to import Union instead of using a pipe bothers me. It's useless boilerplate and verbose. So not o Python. I reported it, but Guido told me it will not happen.
- pas 7y agoExplicit is good in Python world. And I have to agree with him. Just look at the mess sclalaz did/does with its use of clever pictogram-like symbol names. Python is very much a language where newcomers are the norm. Make the source code at least a bit self-teaching seems like a good feature.
- sametmax 7y agoYou are right. Let's remove the "+" operator in favor of operator.add. It's totally worth the readability. I'm sorry but "|" is not only a very commonly known operator in the entire programming world, it is already an officially supported operator by python, vastly used by the community for doing unions: sets use it, sqlalchemy use it, pandas use it. Let's not confuse explicite and paperwork.
- maattdd 7y agoIt is not unique, union type and path aware type system will do this, for example in Crystal: https://crystal-lang.org/reference/syntax_and_semantics/union_types.html https://crystal-lang.org/reference/syntax_and_semantics/unio...
- dtech 7y agoFairly unique as in the only mainstream programming language that can do this
- ajxs 7y agoNot to nitpick too much, but wouldn't the function expecting an interface be a much better fit for a case like this?
- dtech 7y agoYou can name the things I left anonymous, wouldn't change the principles. The Typescript docs have more details and advantages for this specific scenario: https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions https://www.typescriptlang.org/docs/handbook/advanced-types....