使用字符串模板类型

IGJ0hu.jpg

问题

继续上一节我们的问题 还是这个对象

export const fruitCounts = {
	pear: 5,
	apple: 9,
	banana: 3
}

我们需要的类型是这样的:

type SingleFruitCount = |
	{pear: number; pearPrice: number} |
	{apple: number; applePrice: number} |
	{banama: number; bananaNumber: number}

即每个对象有多了一个属性,该属性的key和已有的一个属性的名字有关。 那么这个时候我们该怎么处理呢?

在线试一试

剧透预警线

解答

首先我们先把上一节的答案拿过来,我们在其基础上修改

export const fruitCounts = {
	pear: 5,
	apple: 9,
	banana: 3
}

type FruitCounts = typeof fruitCounts

type SingleFruitCount = {
	[Key in keyof FruitCounts]: {
		[K in Key]: number
	}
}[keyof FruitCounts]

我们只需要给 SingleFruitCount 里每个对象再多添加一个属性即可:

type SingleFruitCount = {
	[Key in keyof FruitCounts]: {
		[K in Key]: number
	} & Record<`${Key}Price`,number>
}[keyof FruitCounts]

完整代码:

export const fruitCounts = {
	pear: 5,
	apple: 9,
	banana: 3
}

type FruitCounts = typeof fruitCounts

type SingleFruitCount = {
	[Key in keyof FruitCounts]: {
		[K in Key]: number
	} & Record<`${Key}Price`,number>
}[keyof FruitCounts]

// 验证
const apple: SingleFruitCount = {
	apple: 10,
	applePrice: 4
}

知识点

  1. 字符串模板类型
  2. Record