25

Given a class like this:

class Example {
    always: number;
    example?: number;

    a?: {
        b?: {
            c?: number;
        }
    };

    one?: {
        two?: {
            three?: number;
            four?: number;
        }
    };
}

Is it possible to, for example, mark a.b.c and one.two.three as non-optional (required) properties, without changing example and possibly also without changing one.two.four?

I was wondering if there was some recursive version of MarkRequired from ts-essentials.

Use case:

We have a ReST-like API that returns data where some properties are always defined, and others are optional and explicitly-requested by the client (using a query string like ?with=a,b,c.d.e). We'd like to be able to mark the requested properties and nested properties as not including undefined, to avoid having to do unnecessary undefined checks.

Is something like this possible?

8
  • 1
    Typescript cannot "parse" things such as "a.b" (just a string) into meaning nested properties, so if that is part of what you're looking for (and I think it is), the answer is no. If you're more flexible on the syntax it's a different story.
    – Ingo Bürk
    Commented Sep 7, 2019 at 19:44
  • 1
    If you're okay with a syntax like MarkRequired<Example, { a: { b: { c: any } }; one: { two: { three: any } } }>, let me know and I'll post an answer.
    – jcalz
    Commented Sep 8, 2019 at 0:07
  • Isn't this exactly what non-null assertions are for? Commented Sep 8, 2019 at 0:27
  • 1
    @Patrick Roberts Then you're putting that burden on the consumer of the API, though. I think OP here wants to return a properly typed response that already includes this.
    – Ingo Bürk
    Commented Sep 8, 2019 at 10:12
  • @Ingo Bürk No, I was quite sure that TS wouldn't be able to understand the a.b syntax, the question was more about marking a as required and then having properties under it also marked as required. Thanks.
    – glen-84
    Commented Sep 8, 2019 at 12:35

4 Answers 4

18

So here is what I came up with to create a recursive DeepRequired type.

Input

Two generic type parameters:

  1. T for the base type Example
  2. P for an union type of tuples, that represent our "required object property paths" ["a", "b", "c"] | ["one", "two", "three"] (similar to lodash object paths via get)

Example flow

  1. Grab all required properties in top level P[0]: "a" | "one"
  2. Create intersection type/concatenation of required and non required object properties

We include all properties from Example and additionally create a mapped type to remove ? and the undefined value for each optional property that is to be changed to required. We can do that by using the built-in types Required and NonNullable.

type DeepRequired<T, P extends string[]> = T extends object
  ? (Omit<T, Extract<keyof T, P[0]>> &
      Required<
        {
          [K in Extract<keyof T, P[0]>]: NonNullable<...> // more shortly 
        }
      >)
  : T;
  1. The type must be somehow recursive for sub properties. That implies, we also have to find a way to "shift" types from the tuple T to iteratively get the next required sub property in the path. To do that, we create a helper tuple type Shift (more on the implementation shortly).
type T = Shift<["a", "b", "c"]> 
       = ["b", "c"]
  1. Challenging thing is, we want to pass in an union of tuples (aka many required paths), not just one. We can make use of distributive conditional types for this and use another helper ShiftUnion capable to distribute unions of tuples over the conditional type containing Shift:
type T = ShiftUnion<["a", "b", "c"] | ["one", "two", "three"]> 
       = ["b", "c"] | ["two", "three"]
  1. We then can get all required properties for the next sub paths by simply selecting the first index:
type T = ShiftUnion<["a", "b", "c"] | ["one", "two", "three"]>[0] 
       = "b" | "two"

Implementation

Main type DeepRequired

type DeepRequired<T, P extends string[]> = T extends object
  ? (Omit<T, Extract<keyof T, P[0]>> &
      Required<
        {
          [K in Extract<keyof T, P[0]>]: NonNullable<
            DeepRequired<T[K], ShiftUnion<P>>
          >
        }
      >)
  : T;

Tuple helper types Shift/ShiftUnion

We can infer the tuple type, that is shifted by one element, with help of generic rest parameters in function types and type inference in conditional types.

// Analogues to array.prototype.shift
export type Shift<T extends any[]> = ((...t: T) => any) extends ((
  first: any,
  ...rest: infer Rest
) => any)
  ? Rest
  : never;

// use a distributed conditional type here
type ShiftUnion<T> = T extends any[] ? Shift<T> : never;

Test

type DeepRequiredExample = DeepRequired<
  Example,
  ["a", "b", "c"] | ["one", "two", "three"]
>;

declare const ex: DeepRequiredExample;

ex.a.b.c; // (property) c: number
ex.one.two.three; // (property) three: number
ex.one.two.four; // (property) four?: number | undefined
ex.always // always: number
ex.example // example?: number | undefined

Playground


Some polish (Update)

There is still some minor inaccuracy left: If we add property two also under a, e.g. a?: { two?: number; ... };, it also gets marked as required, despite not beeing in our paths P with ["a", "b", "c"] | ["one", "two", "three"] in the example. We can fix that easily by extending the ShiftUnion type:

type ShiftUnion<P extends PropertyKey, T extends any[]> = T extends any[]
  ? T[0] extends P ? Shift<T> : never
  : never;

Example:

// for property "a", give me all required subproperties
// now omits "two" and "three"
type T = ShiftUnion<"a", ["a", "b", "c"] | ["one", "two", "three"]>;
       = ["b", "c"]

This implementation excludes equally named properties like two, that are in different "object paths". So two under a is not marked required anymore.

Playground

Possible extensions

  • For single required properties pass in strings instead of tuple paths for convenience.
  • Current implementation is suitable for a few object paths to be marked required; if multiple nested sub properties from an object are to be selected, the solution could be extended to receive object literal types instead of tuples.

Hope, that helps! Feel free to use that as a base for your further experiments.

8
  • 1
    This is amazing, thank you. When it's just one property, like example, it might be cool if that didn't have to be a tuple (like "example" | ["one", "two"]), but that's just a minor thing that wouldn't be worth implementing if it complicated things.
    – glen-84
    Commented Sep 8, 2019 at 12:37
  • 1
    @glen-84 Thanks! That single string type would be a possible convenience extension, you're right. Btw: I added a minor fix to the ShiftUnion type, have a look at the updated answer.
    – ford04
    Commented Sep 10, 2019 at 9:20
  • 1
    Now with template literal types I bet this could be rewritten to work with a string syntax like "one.two.three" :)
    – osdiab
    Commented Dec 30, 2020 at 5:48
  • 1
    Yep, this type will convert a string type like "a.b.c.d" to ["a", "b", "c", "d"] so you can use the above answer with the following for a more familiar syntax :) type PathToStringArray<T extends string> = T extends `${infer Head}.${infer Tail}` ? [...PathToStringArray<Head>, ...PathToStringArray<Tail>] : [T]
    – osdiab
    Commented Dec 30, 2020 at 6:01
  • 1
    @osdiab the purpose of T extends any is to distribute each union member over the extends clause, so that ShiftUnion<"a", ["a", "b"] | ["a", "c"]> becomes ["b"] | ["c"] (see TS docs).
    – ford04
    Commented Dec 31, 2020 at 9:46
18

This worked well for me:

//Custom utility type:
export type DeepRequired<T> = {
  [K in keyof T]: Required<DeepRequired<T[K]>>
}

//Usage:
export type MyTypeDeepRequired = DeepRequired<MyType>

The custom utility type takes any type and iteratively sets it's keys to required and recursively calls deeper structures and does the same. The result is a new type with all parameters on your deeply nested type set to required.

I got the idea from this post where he makes a deeply nested type nullable:

type DeepNullable<T> = {
  [K in keyof T]: DeepNullable<T[K]> | null;
};

https://typeofnan.dev/making-every-object-property-nullable-in-typescript/

Thus, this method could be used to change arbitrary attributes of the deeply nested properties.

4
  • 1
    I think that you might have missed the "on specific properties" part of the question. 🙂 BTW, you can shorten DeepRequired<T> by using [P in keyof T]-?: DeepRequired<T[P]>;.
    – glen-84
    Commented Jun 4, 2021 at 20:28
  • 8
    For anyone who finds this: type DeepRequired<T> = { [K in keyof T]: DeepRequired<T[K]>} & Required<T> is probably the best thing to use.
    – Zarjio
    Commented Feb 25, 2022 at 18:12
  • 2
    @Zarjio And why is that?
    – damd
    Commented Jun 22, 2023 at 1:12
  • To clarify, the solution provided by @Zarjio is slightly different from the answer. It is complete in the sense that it marks every property in the type passed to DeepRequired as required, not just the nested ones (which is what the solution in the answer does). Commented Jan 8 at 9:20
14

A slightly modified variant of this answer https://stackoverflow.com/a/67833840/12631321 (I don't have enough reputation to comment) worked great for me and introduced less garbage in intellisense hints:

type DeepRequired<T> = Required<{
    [K in keyof T]: T[K] extends Required<T[K]> ? T[K] : DeepRequired<T[K]>
}>

Idea is that a type is the same as its Required wrapper, then we can skip it using conditional typing.

1
  • Logged in just to upvote :) Worked great for my use-case! (had intellisense functions running me crazy..) Commented Feb 28 at 11:26
7

I augmented ford64's answer with template literal types to allow for specifying the paths using dot-separated strings, which looks a lot more familiar in syntax than arrays of keys. It's not 100% the same since you can't express a key with a . in it; square brackets dont work ([]); and you can express keys in a way that javascript wouldnt allow like a.b-c.d for obj.a[b-c].d; but these are pretty minor, and it would be pretty simple to augment this type to at least support the brackets case if someone really wanted it.

Here's a playground link demonstrating it! I edited the names of the types a bit, simplified some types and got rid of unnecessary uses of any, though I still don't understand how the ShiftUnion type from the previous answer works to solve the issues, so I left it.

Basically you take ford04's answer and just wrap the paths to require in the PathToStringArray type.

type PathToStringArray<T extends string> = T extends `${infer Head}.${infer Tail}` ? [...PathToStringArray<Head>, ...PathToStringArray<Tail>] : [T]

// ford04's answer, then

type DeepRequiredWithPathsSyntax<T, P extends string> = DeepRequired<T, PathsToStringArray<P>>

Result is you can use a dot-separated syntax to make these paths instead of wordy array syntax, like so:

type Foo = { a?: 2, b?: { c?: 3, d: 4 } }
type A = RequireKeysDeep<Foo, "a">; // {a: 2, b?: { c?: 3, d: 4 } }
type B = RequireKeysDeep<Foo, "b">; // {a?: 2, b: { c?: 3, d: 4 } }
type BC = RequireKeysDeep<Foo, "b.c">; // {a?: 2, b: { c: 3, d: 4 } }
type ABC = RequireKeysDeep<Foo, "a" | "b.c">; // {a: 2, b: { c: 3, d: 4 } }

Tests are in the playground link.

6
  • Nice! I was wondering if this was possible when I was reading about template literal types.
    – glen-84
    Commented Dec 30, 2020 at 17:41
  • I don't suppose there's a way to make this work with arrays? It does work for a specific index, like roles.0.id, but it'd be awesome if we could use something like roles.*.id or roles.[number].id.
    – glen-84
    Commented Apr 28, 2021 at 11:00
  • The other thing that I'm looking for is to just Pick the properties, instead of marking them as required. f.e. Pick<Foo, "a" | "b.c"> or Pick<Foo, "a" | "b"> (where all properties of b are picked, in addition to a).
    – glen-84
    Commented May 10, 2021 at 10:55
  • The former is probably possible - the type would get more complex but basically when you see * you'd replace that with any in the array. It would break keys that have a * in it but who uses those in key names? The latter is pretty simple - use the PathToStringArray helper above, then I believe this should work: type PickDeep<T, P extends string> = Pick<T, PathToStringArray<P>[number]>
    – osdiab
    Commented May 11, 2021 at 11:55
  • oh nevermind taht doesn't work but for PickDeep but its definitely possible in the same way that DeepRequired works, just haven't taken the time to work it out.
    – osdiab
    Commented May 11, 2021 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.