Typescript:定义函数,转换对象并保留键

Art*_*ner 9 typescript

我需要定义一个函数,它接受这种类型的对象:

interface Source<A> {
    [index: string]: A
}
Run Code Online (Sandbox Code Playgroud)

并转换该对象,保留键,但替换值:

interface Target<B> {
    [index: string]: B
}
Run Code Online (Sandbox Code Playgroud)

我还想继续对这种情况进行类型检查。这是示例:

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
Run Code Online (Sandbox Code Playgroud)

cae*_*say 7

现在可以通过keyof关键字实现这一点。

type Mock<K, T> = {
    [P in keyof K]: T
}
Run Code Online (Sandbox Code Playgroud)

这将创建一个具有 type 的所有属性的类型K,但这些属性的值类型将是T.

然后,您可以修改函数以返回Mock<A, B>,编译器将强制执行它。