Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unknown types should not able to concat with strings #29963

Open
hronro opened this issue Feb 19, 2019 · 3 comments
Open

unknown types should not able to concat with strings #29963

hronro opened this issue Feb 19, 2019 · 3 comments
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@hronro
Copy link

hronro commented Feb 19, 2019

TypeScript Version: 3.3.0

Code

declare const a: unknown;
const b = a + 123;
const c = a + '123';
const d = `${a}123`;

Expected behavior:
All the declarations of variables b c d should have errors.

Actual behavior:
Only declaration of variable b have error.

Playground Link:
https://www.typescriptlang.org/play/index.html#src=declare%20const%20a%3A%20unknown%3B%0Aconst%20b%20%3D%20a%20%2B%20123%3B%0Aconst%20c%20%3D%20a%20%2B%20'123'%3B%0Aconst%20d%20%3D%20%60%24%7Ba%7D123%60%3B%0A

Although we won't get runtime errors in this case, it may cause unpredictable result, e.g. "[[Object]]123", which is unexpected, so I think ts should not allow unknown types to concat with strings.

@jack-williams
Copy link
Collaborator

Flagging an error here would be correct from the POV that symbol is a subtype of unknown, and you are not allowed to apply + to symbols.

@hronro
Copy link
Author

hronro commented Feb 21, 2019

Sorry I don't understand what symbol means here. The problem now is unknown type + number would get an error, but unknown type + string won't get an error.

@jack-williams
Copy link
Collaborator

Ah sorry, I mean the symbol type here. Currently you are allowed to concat many things to a string without error, but symbol is not one.

declare const w: Function;
declare const x: { x: number };
declare const y: boolean;
declare const z: symbol;

w + "world";
x + "world";
y + "world";
z + "world"; // Error

So + with a string is very permissive, but not in the case of symbol. Given that something of type unknown could be a symbol, then the safe thing is to flag an error as you suggest. With symbol you will get a runtime error.

@RyanCavanaugh RyanCavanaugh added Suggestion An idea for TypeScript In Discussion Not yet reached consensus labels Feb 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants