Utilizing indexed access types can be beneficial in this scenario. When you have a type resembling an object, denoted as T
, and another type serving as keys for T
, labeled as K
, where T[K]
represents the value type associated with that key. Essentially, if you possess a variable t
of type T
and another variable k
of type K
, then t[k]
will yield the type T[K]
.
The initial step here involves obtaining the type of the functions
property from the AWS
type:
type Funcs = AWS["functions"];
/* type Funcs = {
[k: string]: {
name?: string | undefined;
events?: {
__schemaWorkaround__: null;
} | {
schedule: string | {
rate: string[];
enabled?: boolean;
name?: string;
description?: string;
input?: string;
};
} | undefined;
};
} | undefined */
In this block of code, AWS
corresponds to the placeholder for T
in T[K]
, while the string literal type "functions"
represents the K
type.
Given that functions
is an optional property within AWS
, the Funcs
type entails a union between the declared type of said property and undefined
. This delineation serves a purpose because when operating on a value like aws
of type AWS
, there exists a possibility that aws.functions
could be undefined
. Since merely indexing into a potentially undefined
value poses a risk, the compiler prohibits direct usage of an indexed access type to navigate through Funcs
. A syntax such as Funcs[string]
would result in an error message.
The subsequent task revolves around eliminating the undefined
type from Functions
. The most straightforward approach to achieve this objective incorporates leveraging the NonNullable<T>
utility type, which effectively filters out occurrences of null
and undefined
within a union type T
:
type DefinedFuncs = NonNullable<Funcs>;
/* type DefinedFuncs = {
[k: string]: {
name?: string | undefined;
events?: {
__schemaWorkaround__: null;
} | {
schedule: string | {
rate: string[];
enabled?: boolean;
name?: string;
description?: string;
input?: string;
};
} | undefined;
};
} */
Subsequently, we now possess a defined type encompassing a string
index signature wherein the property type aligns with our target category. Given that any key with a string
value can retrieve the desired property, an indexed access type utilizing DefinedFuncs
as the object type and string
as the key type becomes feasible:
type DesiredProp = DefinedFuncs[string];
/* type DesiredProp = {
name?: string | undefined;
events?: {
__schemaWorkaround__: null;
} | {
schedule: string | {
rate: string[];
enabled?: boolean;
name?: string;
description?: string;
input?: string;
};
} | undefined;
} */
All appears satisfactory! Moreover, the entire process can be condensed into a single line of code:
type DesiredProp = NonNullable<AWS["functions"]>[string];
Access the Playground link for the source code