如何使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
1条答案
按热度按时间gc0ot86w1#
可以使用泛型实用程序类型来验证给定类型:
TS将足够聪明地通过
HasDate
推断T
。Playground
由于
{ [x: string]: Date }
意味着所有键都必须有Date值,所以PropA
显然不是这种情况,所以data2
和data3
失败。