TypeScript Version:
2.3.2
Code
let req: XMLHttpRequest = new XMLHttpRequest();
let rt: string = "text";
req.responseType = rt;
// error TS2322: Type 'string' is not assignable to type 'XMLHttpRequestResponseType'.
Declaring the type of rt to be either XMLHttpRequestEventTarget or ""|"text"|"arraybuffer"|"blob"|"document"|"json" instead of string is necessary to avoid the error message. Equally, casting to any of these types at assignment time works.
Expected behavior:
Setting a variable of string type for responseType should be valid, based on its typing in lib.d.ts:
interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
// ...
responseType: string;
// ...
}
string type was originally accepted in the following configuration: "ts-loader": "2.0.1", "typescript": "2.2.1".
It is no longer accepted in the following configurations: "ts-loader": "2.0.3", "typescript": "2.2.1" and "ts-loader": "2.0.3", "typescript": "2.3.2", so I think it is related to the version of ts-loader.
If compilation requires XMLHttpRequestResponseType, then why isn't it specified in the interface? Please confirm whether this is just a problem with my setup. Note that WebStorm says "cannot find declaration to go to" when I cmd-click XMLHttpRequestResponseType.
Actual behavior:
Assigning responseText to a variable of string type throws an error at compile-time: error TS2322: Type 'string' is not assignable to type 'XMLHttpRequestResponseType'.
We don't know that rt is a correct response type as its literal value is not maintained due to it being a let. If you write this, there's no error:
let req: XMLHttpRequest = new XMLHttpRequest();
const rt = "text";
req.responseType = rt; // OK
@RyanCavanaugh, your answer makes total sense.
I actually hit this too while trying to update RxJS to 2.3... It unfortunately puts a little more burden on the developer, and I'm not totally sure the trade off is worth it in this particular case. But that's just an opinion. It's probably fine in the 80% case I guess.
Most helpful comment
We don't know that
rtis a correct response type as its literal value is not maintained due to it being alet. If you write this, there's no error: