#Lookup type on nullable
55 messages · Page 1 of 1 (latest)
depends what kind of result you are expecting
NonNullable<Xyz["y"]>["z"]
if you want to ignore the null part of the type
but I wouldn't recommend it
because if you use that type as a cast on a value, then you are hiding something that could be a problem
don't know what you mean by "utility type"
every type can be a utility type
no, if you wish to make that z type reusable
then it's type Z<T extends { y: { z: unknown } | null }> = NonNullable<T["y"]>["z"];
what would U be?
no
PropertyKey is too generic, it just means "it's a key"
you'd just get "a value" back
not precise and useful at all
what are you exactly expecting from that Lookup type?
how would you use it?
type Dog = { name: string, collar: { brand: string, material: string } | null }
type DogsCollar = Lookup<Dog, "collar"> // { brand: string, material: string }
something like this
you don't need an utility type for that tbh
it's too simple
type Lookup<T extends Record<U, unknown>, U extends PropertyKey> = T[U];
would be just as short to type Dog["collar"]
instead of Lookup<Dog, "collar">
Oh, wait sorry
type Dog = { name: string, collar: { brand: string, material: string } | null }
type DogsCollar = Lookup<Dog["collar"], "material"> // string
That's what I meant
again, Dog["collar"]["material"]
can't be simpler than that
oh, wait
the null part
tbh just adding the NonNullable yourself where you need would be easier
NonNullable<Dog["collar"]>["material"]
Lookup<Lookup<Dog, "collar">, "collar"> would be just as long
and less straightforward
if NonNullable is too long, just create an alias type NN<T> = NonNullable<T>;
Yes, although I thought it would be safer since you said NonNullable kind of casts a type
no, that's not what I meant
the types are fine on their own
the real risk is how you use those types
but I feel like you don't really need that type, do you?
NonNullable?
Lookup
yes, in that case I don't
like, if you have a object that might be null
simply make sure it is not null
with a simple if check
and if it's not, then access the properties
I'm using it to set expected types based on queries types, I've never thought I'd need to do such thing as well
And since query returned object types differ from standard types (like type for returned object of let's say ArticleQuery differs from Article)
it's really the only source for me to get what I want
oh, ok, I see
is this your actual code?
because it could be improved
interface Dog {
name: string;
collar: DogsCollar | null;
}
interface DogsCollar {
brand: string;
material: string;
}