What about to use type in assignments by default?
Without extra code, like this:
let a := 23 // syntax sugar for `let a :number = 23`
a = "some string" // type error
function foo(x := 0) {
if (x) {
return x // type error
}
return: "default string" // assign `string` type to `foo`
}
Adding new operators is out of scope for Flow.
it not new operator, it just syntax sugar. It is extended = operator, with types.
This is the way to reduce "unimportant" code.
From syntactic point of view this _is_ a new operator.
Ok. Let see from other side:
let a :number = 23
can wee omit word number in cases where wee know type, from assignment?
let a : = 23
And it still will be a new operator.
If := is out of scope then maybe something like an explicit auto type could be used here? E.g.:
let a : auto = 23; //equivalent let a : number = 23;
function foo(x : auto = 0) { /* */ }
For simple types like above the advantage is of course minimal, but for more complex generic types this can be very helpful.
@TiddoLangerak Such implicit behaviour will break code self-documenteding.
@TrySound I think the amount of self-documentation is up to authors of the code, that's not necessarily the responsibility of flow. There are many legitimate situations where the exact type isn't very important, or is already abundantly clear from the context (e.g. const x = new SomeClass()). Flow already allows you to omit types, but then it infers the type from the entire context. An auto type can be used to force it to infer the type from the current expression. E.g. consider this snippet:
function double(x = 0) {
return x * 2; // <-- Error: the operand of an arithmetic operation must be a number
};
double('asdf'); //<-- no error here, even though the actual bug is here.
With an auto type you would get:
function double(x : auto = 0) {
return x * 2;
};
double('string'); // <-- Error: This type is incompatible with the expected param type of number
In this trivial example you could of course replace auto with number, but in real-world scenarios this is not always easy to do, or even possible, since the relevant types might not be available.

Most helpful comment