tuchk4
tuchk4

Reputation: 2350

Generic arguments of the interface method

There is interface:

interface BaseConfig<T = number> {
  doSomething(value: T): void;
}

There is a function that accepts this interface at the arguments:

function test(config: BaseConfig<number> | BaseConfig<string>) {}

Question: Why value is any? I expect it to be string | number.

test({
  doSomething(value) {} // <-- value is any
});

Link to playground

NOTE: If use generic not at the arguments, but at the response – everything is OK.

interface BaseConfig<T = number> {
  doSomething(): T;
}

function test(config: BaseConfig<number> | BaseConfig<string>) {}

test({
  doSomething() {
    return 1; // exepct to return only number ot string
  },
});

Link to playground

Upvotes: 1

Views: 39

Answers (1)

satanTime
satanTime

Reputation: 13539

combine types inside of the generic

function test(config: BaseConfig<number | string>) {}

the problem with BaseConfig<number> | BaseConfig<string> is that TS doesn't combine similar types in case of union, read it as A | B.

it means the config can be either BaseConfig<number> or BaseConfig<string> and when you declare doSomething(value) {} typescript doesn't know whether it is BaseConfig<number> or BaseConfig<string> and leaves it up to you to provide type (simply add value: number or value: string). (it's enough to implement one type, not both of them).

When without union TS knows that it's exactly BaseConfig<number | string> and value is its generic which is number | string.

Upvotes: 1

Related Questions