Poyraz Yilmaz
Poyraz Yilmaz

Reputation: 5857

Dynamic return type

I write a util function which returns an object with the property name I provided.

function example(fieldName: string) {
    return {
        [fieldName]: 'Value',
    };
}

I need to declare a return type for this but as you guess it returns depends on given fieldName parameter.

It should be something like this. When I send example as parameter it return type should be like this

{
    example: string;
}

Upvotes: 0

Views: 446

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You need a type parameter to capture the literal type of the string passed. With this you can use Record to create a type with that key and a specific value type:

function example<K extends string>(fieldName: K): Record<K, string> {
    return {
        [fieldName]: 'Value',
    };
}

let e = example("foo");
e.foo //ok
e.notFoo //err

This will work if the passed in argument is a string literal or something else that is of a string literal type. If the type of the argument is string you will not get any type checking:

let k = "foo" as string;
let e = example(k); // Record<string, string>
e.foo //ok
e.notFoo //still ok 

Upvotes: 2

Related Questions