Dartess
Dartess

Reputation: 53

Type guard don't work with generic params?

Example:

type SomeType = {
    foo: string;
} | undefined;

function someFn<TParams extends SomeType>(params1: SomeType, params2: TParams): void {
  if (params1) {
    Object.entries(params1);
  }
  if (params2) {
    Object.entries(params2); // here is an error
  }
}

TypeScript cannot determine that params2 does not contain undefined. Is there a logical explanation for this, or is it a mistake in TypeScript?

Online demo here

Upvotes: 1

Views: 147

Answers (1)

ccarton
ccarton

Reputation: 3666

This is an open issue in typescript (https://github.com/microsoft/TypeScript/issues/4742). Automatic type guards and generics don't always work together. As a possible work around you could define this type guard manually:

type SomeType = {
    foo: string;
} | undefined;

function isDefined<T> (v: T): v is Exclude<T, undefined> {
  return v !== undefined
}

function someFn<TParams extends SomeType>(params1: SomeType, params2: TParams): void {
  if (params1) {
    Object.entries(params1);
  }
  if (isDefined(params2)) {
    Object.entries(params2);
  }
}

Upvotes: 2

Related Questions