1

Why a object with value:number field can't be assigned to the Partial of a generic interface with value:number

interface ValueNumber {
  value: number;
}

type ValueNumberMaybeUndefined = Partial<ValueNumber>;

function testfunc<T extends ValueNumberMaybeUndefined>() {
  const a: Partial<T> = {
    value: 1,
  };
}

Can anyone explain this?

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
Wilkin Wendy
  • 223
  • 2
  • 15

1 Answers1

0

The type of T is specified by the caller of the function. testfunc therefore does not know the shape of T in advance. When you use T in a generic type like Partial, the expression will essentially be opaque to the compiler and it will not try to evaluate it further making it hard to assign anything to it.

But a type assertion will let you assign something to a variable of type Partial<T>.

function testfunc<T extends ValueNumberMaybeUndefined>() {
  const a = {
    value: 1,
  } as Partial<T>;
}

Playground

Tobias S.
  • 21,159
  • 4
  • 27
  • 45