Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: define function, which transforms an object, keeping keys

Tags:

typescript

I need to define a function, which accepts an object of this type:

interface Source<A> {
    [index: string]: A
}

and transforms that object, keeping the keys, but replaces a values:

interface Target<B> {
    [index: string]: B
}

and I also want to keep typechecking for that case. This is example:

function transform(source) {
    var result = {}
    Object.keys(source).forEach((key) => {
        result[key] = source[key] + "prefix"
    })
}

var target = transform({
    "key1": 1,
    "key2": 2,
})

// now target has a {"key1": "1prefix", "key2": "2prefix"}

var three = target.key3 // I want to get type error here on compile-time
like image 522
Artur Eshenbrener Avatar asked Dec 14 '15 12:12

Artur Eshenbrener


People also ask

How would you define type for object keys in TypeScript?

Use the keyof typeof syntax to create a type from an object's keys, e.g. type Keys = keyof typeof person . The keyof typeof syntax returns a type that represents all of the object's keys as strings.

What is K in TypeScript?

The extends keyword is used to apply constraints to K , so that K is one of the string literal types only. extends means “is assignable” instead of “inherits”; K extends keyof T means that any value of type K can be assigned to the string literal union types.

How do you return an object in TypeScript?

To declare a function with an object return type, set the return type of the function to an object right after the function's parameter list, e.g. function getObj(): {name: string;} {} . If the return type of the function is not set, TypeScript will infer it.


1 Answers

This is now possible with the keyof keyword.

type Mock<K, T> = {
    [P in keyof K]: T
}

This will create a type which has all of the properties of type K, but the value type of those properties will be T.

You could then modify your function to return Mock<A, B> and the compiler would enforce it.

like image 151
caesay Avatar answered Sep 30 '22 18:09

caesay