In TypeScript limit a generic to list of dot notation keys
When working with TypeScript, you may come across a situation where you want to limit a generic type to a specific set of dot notation keys. This can be useful when you want to ensure that only certain properties are allowed to be accessed or modified.
There are multiple solutions to achieve this limitation. Let’s explore two common approaches:
Solution 1: Using mapped types
One way to limit a generic to a list of dot notation keys is by using mapped types in TypeScript. Mapped types allow you to create new types based on existing ones by transforming each property in the original type.
type DotNotationKeys = {
[K in keyof T]: K extends string ? `${K}` : never;
}[keyof T];
// Example usage
type AllowedKeys = DotNotationKeys<{ foo: number; bar: string; baz: boolean }>;
// AllowedKeys will be "foo" | "bar" | "baz"
In this example, the DotNotationKeys
type takes a generic type T
and uses mapped types to transform each property key into a string literal type. The resulting type is an union of all the transformed keys, representing the allowed dot notation keys.
Solution 2: Using conditional types
Another approach to limit a generic to a list of dot notation keys is by using conditional types. Conditional types allow you to create types that depend on a condition.
type DotNotationKeys = T extends object
? keyof T extends string
? `${keyof T}`
: never
: never;
// Example usage
type AllowedKeys = DotNotationKeys<{ foo: number; bar: string; baz: boolean }>;
// AllowedKeys will be "foo" | "bar" | "baz"
In this example, the DotNotationKeys
type uses conditional types to check if the generic type T
is an object and if its keys are of type string. If the condition is met, the property keys are transformed into string literal types using template literal types. Otherwise, the type is set to never
.
By using either of these solutions, you can limit a generic type to a specific set of dot notation keys in TypeScript. This can help improve type safety and prevent accidental access or modification of properties that should not be allowed.
Feel free to choose the solution that suits your needs best and integrate it into your TypeScript projects.
Happy coding!
Leave a Reply