如何确保参数在TypeScript中具有特定属性

6jjcrrmo  于 2023-01-10  发布在  TypeScript
关注(0)|答案(1)|浏览(109)

如何使data2和data3工作,而data1错误,类型类似于下面的代码?
我想确保如果用户只输入params {name: 'aa', age: 20},这是一个错误,因为参数需要包括数据类型date(键名可以是任何名称),如{name: 'aa', age: 20, born: new Date('10-10-2020')

const data1 = {
  name: 'Lorem',
  age: 12
}

const data2 = {
  name: 'Lorem',
  age: 12,
  born: new Date('10/10/1990')
}

const data3 = {
  name: 'epsum',
  age: 12,
  died: new Date('10/10/1990')
}

interface PropsA {
  name: string;
  age: number;
}

const test = (inputParams: PropsA & { [x: string]: Date }) => {
  return inputParams
}

test(data1) //it should be an error because it doesn't have a value with data type Date other than age and name

//how to make this work and not error?
test(data2) 
test(data3)

Playground

gc0ot86w

gc0ot86w1#

可以使用泛型实用程序类型来验证给定类型:

type HasDate<T> = Date extends T[keyof T] ? T : never;

const test = <T extends PropsA>(inputParams: HasDate<T>) => {
  return inputParams;
};

TS将足够聪明地通过HasDate推断T

test(data1) // ! errors
test(data2) // ok
test(data3) // ok

Playground
由于{ [x: string]: Date }意味着所有键都必须有Date值,所以PropA显然不是这种情况,所以data2data3失败。

相关问题