typescripttypescript-generics

Typescript Required type does not work with generics


I came across an interesting type error while trying to use Required<> type transformer with generic. Typescript is 5.9.2

Here's an example:

interface I {
    foo?: number
}

function worksWell(i: Required<I>) {
    const foo: number = i.foo;
}

function hasTypeError<T extends I = I>(i: Required<T>) {
    const foo: number = i.foo; // Error: Type 'number | undefined' is not assignable to type 'number'
}

Here's an example on playground.

Anyone has an explanation? Am I doing something wrong or is it a bug in TS?


Solution

  • type Required<T> = {
        [K in keyof T]-?: Exclude<T[K], undefined>;
    }
    

    Here's the Required which really works.