I'm struggling to define a generic type in TypeScript that makes certain properties of Product
optional while still allowing them to be nullable. I'm still learning TypeScript and finding it quite challenging.
class Product {
id: number | string;
name: null | string;
variants?: ProductVariant[];
}
This is what I've attempted so far:
// Issue: undefined values are still permitted
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{ [key in K]: T[key] }>
https://i.sstatic.net/YRdx9.png
// Problem: 'name' property is no longer nullable
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{ [key in K]: NonNullable<T[key]> }>
https://i.sstatic.net/4PbSQ.png
// Challenge: not handling both null AND undefined values
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{
[key in K]: null extends T[key] ? T[key] :NonNullable<T[key]>
}>