Hitmands
Hitmands

Reputation: 14199

Literal Type inference - Typescript

considering this definition:

interface Domain<Model, Name extends string> {
  name: Name;
  edit(cb: (m: Model) => Model): Domain<Model, Name>;
}

declare function createDomain<
  M extends { [key: string]: any } = {},
  N extends string = string
>(name: N): Domain<M, N>;

the IDE is able to give you correct inspection (as shown in figure): enter image description here this because typescript is able to infer 'foo' as literal type which extends N /* string */.

but

if I provide a signature for the generic M, then typescript looses the information about 'foo' and returns a generic string. enter image description here

how can I change the above definition to preserve the information about N?

Upvotes: 4

Views: 340

Answers (1)

Rodris
Rodris

Reputation: 2858

I see these options:

Provide the second type

let domain = createDomain<Todo, "foo">("foo");

Build a factory

function funcCreateDomain<M>() {
    return <N extends string>(name: N) => createDomain<M, N>(name);
}

let factory = funcCreateDomain<Todo>();
let domain = factory("foo");

Upvotes: 2

Related Questions