-
Notifications
You must be signed in to change notification settings - Fork 12.8k
String literal types in complex type expressions #7199
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
Comments
I could do var fooBar:FooBar = mix({
ok:"ok",
okToo: 42,
notOk:"k"
}) as FooBar ; but then I loose all the benefits of type checking... |
I think you're expecting too much from type argument inference. Give |
var foo: Foo = {
ok:"ok",
okToo: 42,
notOk:"k"
};
var fooBar = mix(foo); Should work fine. TS only infers literal types when there is a type annotation implying them. |
It is as @weswigham explained. Though we may be should consider give a better error message especially this part of the error is a bit misleading
|
The problem is that, in the object literal passed to var foobar: FooBar = mix({
ok:"ok",
okToo: 42,
notOk: "k" as "k" // or as "o" | "k"
}); The error message you get without the annotation looks completely wrong to me, or at least misleading. @DanielRosenwasser has a PR #6554 that defaults string literals to string literal types, and then widens to |
@sandersn that solves the problem :-) So, if I define type OK = "o" | "k";
interface Foo {
//...
nowOk: OK;
}
var foobar: FooBar = mix({
//...
nowOk: "k" as OK;
}); |
that should work, or even specifying the type argument explicitlly: var foobar: FooBar = mix<Foo>({
//...
nowOk: "k";
}); |
TypeScript Version:
1.8.2
Code
Expected behavior:
The assignment to
fooBar
should be allowed.Actual behavior:
I get the totally confusing error:
The confusing part is that it complains about the first property (
ok
) and not aboutnotOk
.Looking at the error message it seems that the string literal type
notOk:"o"|"k"
was converted tonotOk :string
.Therefore when I turn the string literal type to a string (
notOk:string
) everything is OK....Hint: defining the string literal type as a type does not solve the problem:
The text was updated successfully, but these errors were encountered: