Skip to content

String literal types in complex type expressions #7199

Closed
@scharf

Description

@scharf

TypeScript Version:

1.8.2

Code

interface Foo {
    ok:string;
    okToo: number;
    notOk:  "o" | "k";
}

interface Bar {
    bar: string;
}

interface FooBar extends Foo, Bar{
}

function mix<T>(obj:T): T & Bar {
    (obj as any).bar="bar";
    return obj as T & Bar;
}

var fooBar:FooBar = mix({
    ok:"ok",
    okToo: 42,
    notOk:"k"
});

Expected behavior:

The assignment to fooBar should be allowed.

Actual behavior:

I get the totally confusing error:

Error:(20, 5) TS2322: Type '{ ok: string; notOk: string; } & Bar' is not assignable to type 'FooBar'.
 Type 'Bar' is not assignable to type 'FooBar'.
 Property 'ok' is missing in type 'Bar'.

The confusing part is that it complains about the first property (ok) and not about notOk.

Looking at the error message it seems that the string literal type notOk:"o"|"k" was converted to notOk :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:

type NotOK =  "o" | "k";

interface Foo {
    //...
    notOk: NotOK;
}
//...

Metadata

Metadata

Labels

BugA bug in TypeScriptDomain: Error MessagesThe issue relates to error messagingFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions