TypeScript 中的键和值类型

Key and value types in TypeScript

interface A { a?: number };
interface B { a?: string };

function copy<
    Source extends object,
    Destination extends { [destinationKey in keyof Source]?: (1) }
>(
    source: Source,
    key: keyof Source,
    destination: Destination,
    transformer: (value: (2)) => (3) 
) {
    if (source[key] !== undefined) {
        destination[key] = transformer ? transformer(source[key]) : source[key];
    }
}

const a: A = { a: 123 };
const b: B = {};

copy(a, "a", b, (value) => value.toString());

在上面的例子中,我可以为以下占位符使用什么:

您需要一个额外的类型参数来表示将传入的实际键。该参数将根据传入 key 参数的值推断为字符串文字类型。有了这个新类型,我们可以使用类型查询来获取 SourceDestination 类型中特定的 属性 类型。

此外,由于我们只关心特定的 K 键,我们可以在定义 Destination 类型时使用它(而不是指定 Destination 必须具有所有键Source)。由于我们并不真正关心目标 属性 的类型,只关心它存在并且 transformer 函数必须 return 与此 属性 类型相同的值] 我们可以将 Destination 中的 属性 的类型指定为 unknown.

interface A { a?: number };
interface B { a?: string };

function copy<
    K extends keyof Source, // The extra type parameter
    Source extends object,
    Destination extends { [destinationKey in K]?: unknown } // Can be anything we don't really care, we only care about the K key existing
>(
    source: Source,
    key: K, // The key is of type K
    destination: Destination,
    transformer: (value: Source[K]) => Destination[K] // We use K to specify the relation between Source and Destination property type
) {
    if (source[key] !== undefined) {
        destination[key] = transformer ? transformer(source[key]) : source[key];
    }
}

const a: A = { a: 123 };
const b: B = {};

copy(a, "a", b, (value) => value.toString());
copy(a, "a", b, (value) => value); /// error