how to make data2 and data3 work and data1 error with type like in the following code?
I want to make sure that if the user just enters params {name: 'aa', age: 20}
it is an error, because parameters need to include data type date(key name can be anything) like {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)
CodePudding user response:
Possible with a generic utility type to validate the given type:
type HasDate<T> = Date extends T[keyof T] ? T : never;
const test = <T extends PropsA>(inputParams: HasDate<T>) => {
return inputParams;
};
TS will be smart enough to infer T
through HasDate
.
test(data1) // ! errors
test(data2) // ok
test(data3) // ok
Your attempt doesn't work since { [x: string]: Date }
means all keys must have Date values. That obviously isn't the case for PropA
, so data2
and data3
fail.