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());

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

  • (1(-Destination中与Source中相应键关联的值的类型
  • (2(-Source中与参数key指定的键关联的值的类型
  • (3(-Destination中与参数key指定的键关联的值的类型

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

此外,由于我们只关心特定的K密钥,因此当我们将Destination类型定义为具有它时,我们可以使用它(而不是指定Destination必须具有Source的所有密钥(。由于我们并不真正关心目标属性的类型,只关心它的存在以及transformer函数必须返回与该属性相同类型的值,因此我们可以将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

最新更新