ecmascript-types
ecmascript-types copied to clipboard
Nested casting for objects
This was brought up in #33. Essentially offering a compact way to cast object properties. As an example say you have an object, possibly returned from another library, and want to cast the individual properties to different types:
const foo = { a: [0, 1, 2] };
const bar = foo:{ (a:uint8[]) }; // Returns a new object: { a:uint8[]:[0, 1, 2] }
or:
const foo = { a: 1, b: 1.234 };
const bar = foo:{ (a:uint8), (b:MyType): c }; // Returns new object: { a:uint8: 1, c:MyType: 1.234 }
This is kind of low priority and doesn't need to really be considered for the spec unless for some reason it couldn't be added later if it was necessary. I don't think it's overly useful, and I'm not convinced the syntax is right. More of a random idea.
Maybe something like :
type BarType { a: uint8[] };
const foo = { a: [0, 1, 2] };
const bar:BarType = foo; // Returns a new object: { a:uint8[]: [0, 1, 2] }
type BarType { a: uint8, c: MyOtherType };
const foo = { a: 1, b: 1.234 };
const bar:BarType = {c: foo.b, ...foo}; // Returns new object: { a:uint8: 1, c:MyOtherType: 1.234 }
Notice the new keyword "type" to define a type.
What do you thing about as
keyword?
Like a keyword used in TypeScript for type assertion and in Rust for type casting.
So my example from #33 can be:
const o: { a: { a2: uint8 } } = { a: { a2: 1 } };
const { a: { a2: b as uint32 } } = o;
And examples from this topic:
const foo = { a: [0, 1, 2] };
const bar = foo as { a as uint8[] };
const foo2 = { a: 1, b: 1.234 };
const bar2 = foo2 as { a as uint8, b: c as MyType };
But this two examples is looks better in @doodadjs version.
Some interesting examples can be found there — https://github.com/Microsoft/TypeScript/issues/7576