Typescript: Incorrect error message with String Literal Types

Created on 30 Jul 2019  路  3Comments  路  Source: microsoft/TypeScript

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:

Bug

Most helpful comment

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

All 3 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

remojansen picture remojansen  路  3Comments

dlaberge picture dlaberge  路  3Comments

siddjain picture siddjain  路  3Comments

zhuravlikjb picture zhuravlikjb  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments