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
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments