In JavaScript is possible to mutate objects inside functions. Right now, the following code in JavaScript:
functionmerge(x,y){Object.assign(x,y);}letx={a: 1};merge(x,{b: 2});console.log(x.b);Can't be written in TypeScript without casting the type. There are a few options whose type definition is wrong in all scenarios I can think of (maybe I'm missing a better option):
Option 1
letx: {a: number,b: number}={a: 1};// Error, missing bmerge(x,{b: 2});Option 2
letx: {a: number,b: number}={a: 1,b: 2};merge(x,{b: null});// From here, x.b is not a number anymore, but you could dolety: number=x.b;Suggestion
There could be an extension to function parameter definition like the following:
// then keyword indicates that before it can be type A, and after it will be of type A&B.functionmerge<A,B>(x: Athenx2: A&B,y: B){Object.assign(x2,y);}letx: {a: number,b: number}={a: 1,b: 2};merge(x,{b: null});// Here, type of x is {a: number, b: number} & {b: null}x.b;// Type nullThere, we indicate that whatever type was x before, now it is something different. The code above could be written in TypeScript as follows:
// then keyword indicates that before it can be type A, and after it will be of type A&B.functionmerge<A,B>(x: A,y: B){Object.assign(x,y);}letx: {a: number,b: number}={a: 1,b: 2};merge(x,{b: null});// Here, type of x is {a: number, b: number} & {b: null}letxAfterMerge=xas{a: number,b: number}&{b: null};// Since this line, x should not be used but xAfterMergexAfterMerge.b;// Type nullAnother example
interfaceBefore{address: string;}interfaceAfter{addr: string;}functionmap(userb: Beforethenusera: After){usera.addr=userb.address;deleteuserb.address;}letu={adress: "my street"};map(u);console.log(u.addr);That could be syntax sugar for this:
interfaceBefore{address: string;}interfaceAfter{addr: string;}functionmap(userb: any){userb.addr=userb.address;deleteuserb.address;}letu={adress: "my street"};map(u);console.log((uasAfter).addr);Syntax
It could be something like:
identifier: type *then* identifier: type
With the identifiers being different, and with the types being mandatory an extension of Object.
In JavaScript is possible to mutate objects inside functions. Right now, the following code in JavaScript:
Can't be written in TypeScript without casting the type. There are a few options whose type definition is wrong in all scenarios I can think of (maybe I'm missing a better option):
Option 1
Option 2
Suggestion
There could be an extension to function parameter definition like the following:
There, we indicate that whatever type was x before, now it is something different. The code above could be written in TypeScript as follows:
Another example
That could be syntax sugar for this:
Syntax
It could be something like:
With the identifiers being different, and with the types being mandatory an extension of Object.