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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With