I was looking through this question here:
The top answer has DeepPartial type defined as follows:
type DeepPartial<T> = {
[P in keyof T]?: DeepPartial<T[P]>;
};
I tested and this type works as expected, but I can't fully understand how this works internally.
let's take example interface from the same question:
interface Foobar {
foo: number;
bar: {
baz: boolean;
qux: string;
};
}
when P=bar, it's easy to understand that recursively it will go into
DeepPartial<{
baz: boolean;
qux: string;
}>
and make "baz" and "qux" keys optional.
But what I don't get is how does the recursion work for primitive types?
Like for foo
key, how is DeepPartial<number>
same as number
? When T=number,
[P in keyof number]?: DeepPartial<number[P]>;
doesn't make sense to me.
In my mind, the implementation of DeepPartial should be something like:
type DeepPartial<T> = {
[P in keyof T]?: isPrimitive(T[P]) ? T[P] : DeepPartial<T[P]>;
};
But original implementation works also, and I don't get how.
I hope I explained my question well enough. Here is example playground:
Edit: I investigated further and found out that
type DeepPartial<T> = {
[P in keyof T]?: any;
};
type DeepPartialTest<T> = {
[P in keyof number]?: any;
};
now DeepPartial<number>
will return number type, but DeepPartialTest<number>
will not. Which makes this even weirder for me.
Edit 2 add screenshots:
This works as expected:
This doesn't:
When in reality both should be the same??
DeepPartial
just makes the keys optional.number
is a primitie and doesn't technically have keys, soDeepPartial<number>
is a no-op42
) but you somehow cannot do(42).toString()
because you cannot removetoString()
from primitives. They are immutable.number
is a primitive, not an object. Primitives are immutable, so it doesn't make sense to have different properties on5
and42
.