TypeScript Version: 3.6.0-dev.20190730
Search Terms:
String Literal Types
Code
type ACT = 'submit';
interface Test {
histories: {
act: ACT,
time: number,
}[],
}
function test(o: Test){
}
test({histories: [{act: 'submit'}]})
Expected behavior:
Property 'time' is missing in type '{ act: ACT; }' but required in type '{ act: ACT; time: number; }'.
Actual behavior:
Type 'string' is not assignable to type '"submit"'.
Playground Link:
Related Issues:
You should use as const to tell compiler that string 'submit' shouldn't be widened to string
Example: http://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAggwgFSgXigcgM4FcBGBbAS2DQG4BYAKAIDtgIAnAMwEMBjaBCDYKAb0qiCoACwLcA9vQJcAXHwFDFbYHPgIANAsWDgBPBDnUseHA00VFAXwDaAXXOXKjLNVa7x1KHW4AKcXM5uAEp+CkpHCm9gH15RCSlZKGteZTlMXEJiKGYMKFYPbktbSyCgA
You should use as const to tell compiler that string 'submit' shouldn't be widened to string
Yes, but the contextual type handles that here if time is specified, so I think that this is surprising.
http://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAggwgFSgXigcgM4FcBGBbAS2DQG4BYAKAIDtgIAnAMwEMBjaBCDYKAb0qiCoACwLcA9vQJcAXHwFDFbYHPgIANAsWDgBPBDnUseHA00VFAXwDaAXXOXKjLNVa7x1KHW4AKcXM5uAEp+CkpHCm9gH15RCSlZKGteZTlMXEJidS89AygAZihLW0sgoA
It seems that this issue has been fixed in version 3.9.2
Most helpful comment
Yes, but the contextual type handles that here if
timeis specified, so I think that this is surprising.http://www.typescriptlang.org/play/index.html#code/C4TwDgpgBAggwgFSgXigcgM4FcBGBbAS2DQG4BYAKAIDtgIAnAMwEMBjaBCDYKAb0qiCoACwLcA9vQJcAXHwFDFbYHPgIANAsWDgBPBDnUseHA00VFAXwDaAXXOXKjLNVa7x1KHW4AKcXM5uAEp+CkpHCm9gH15RCSlZKGteZTlMXEJidS89AygAZihLW0sgoA