How to implement a TypeScript generic type for nested properties that resolves to their types?

Advertisements How to create a generic type that resolves to the type of a nested property Say I have a configuration type type Config = { parent: { child: boolean } } I would like something similar to type ChildConfigType = NestedType<Config, ‘parent.child’> // boolean type ParentConfigType = NestedType<Config, ‘parent’> // {child: boolean} I have… Read More How to implement a TypeScript generic type for nested properties that resolves to their types?

Function that returns the same object shape as it accepted in typescript

Advertisements I’d like to constrain a function such that it accept an object as an argument, and returns an object of the exact same shape. That object’s keys can be any string, and I’d like to tell typescript that the return object has the same keys. I.e. interface ConstrainedObject { [key: string]: string[]; } function… Read More Function that returns the same object shape as it accepted in typescript

How can I index a generic with an with the argument passed in to function in Typescript

Advertisements Suppose I have an interface in typescript as follows: interface I1 { name: string, age: number } And I have another interface that accesses interface properties: interface I2<T> { getValue: (arg0: keyof T) => any } I want to be able to pass in another interface into I2 such that you can only pass… Read More How can I index a generic with an with the argument passed in to function in Typescript

Typescript typing with keyof always has ambigious typing, even when specified

Advertisements type StringTyped = {[key: string]: any}; type ShouldBeStringType = keyof StringTyped; const test:ShouldBeStringType = 2; // but this is allowed? I am trying to have a generic Type that relies on keyof actually returning the type which is specified, but keyof seems to always return the type string | number, even if I specify… Read More Typescript typing with keyof always has ambigious typing, even when specified

Typescript function return type of the optional property as const with default

Advertisements How to return the same type of the parameter if passed to the function, else fallback to another required parameter? const r = <Name extends string, R extends string>({ name, resource }: { name?: Name, resource: R }) => { return { // here the type of the "name" should be same as the… Read More Typescript function return type of the optional property as const with default