Why does the following code pass the Typescript compiler?
type O = {
name: string
city: string
}
function returnString(s: string) {
return s
}
let o1: O = {
name: "Marc",
city: "Paris",
[returnString("random")]: "London",
}
Why does the following code pass the Typescript compiler?
type O = {
name: string
city: string
}
function returnString(s: string) {
return s
}
let o1: O = {
name: "Marc",
city: "Paris",
[returnString("random")]: "London",
}
Why does this surprise you?
The code passes because, for one thing, it's valid plain-old JavaScript as of ES2015.
Even if it wasn't valid JavaScript, since this code can be translated to JavaScript that doesn't directly support computed key values, and it's a very nice, convenient thing to be able to do... why not support it?
As ES2015:
"use strict";
function returnString(s) {
return s;
}
let o1 = {
name: "Marc",
city: "Paris",
[returnString("random")]: "London",
};
Transpiled to ES5:
"use strict";
var _a;
function returnString(s) {
return s;
}
var o1 = (_a = {
name: "Marc",
city: "Paris"
},
_a[returnString("random")] = "London",
_a);
It's because of the : never
type. I believe this is a very advanced typescript concept which is usually used to discriminate unions.
This is not a complete answer but it could serve you like a hint to understand the problem, it loses the scope of the string return value.
type O = {
name: string
city: string
}
declare const neverValue: never;
// This will fail
// function returnStringS(s: string): 's' {
// return 's';
// }
// This will work
function returnStringS(s: string): string {
return 's';
}
// This will work
function returnStringS(s: string): string {
return s;
}
let o1: O = {
name: "Marc",
city: "Paris",
[returnStringS("random")]: "London",
}
let o2: O = {
name: "Marc",
city: "Paris",
[returnString("random")]: "London",
}
const some2: O = {
name: "Marc",
city: "Paris",
[neverValue]: "London"
}
At the Typescript documentation TS never type is the key of this issue/concept.
The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never.