I have these two interfaces
JavaScript
x
10
10
1
interface PersonRequirements{
2
user:string,
3
password:string,
4
id:number
5
}
6
export interface Requirement<R> {
7
name: keyof R & string,
8
save: () => any,/* I want this return type to be same as return type of founded key in R*/
9
}
10
and here is my use case elsewhere
JavaScript
1
7
1
const idRequirement:Requirement<PersonRequirements>={
2
name:"id",
3
save:function ():number/* I want this return type to be same as id's return type(number) but in a generic type safe way*/{
4
//
5
}
6
}
7
I want to make save()
return type to be same as id’s return type but in a generic type safe way how can I do that ?
Advertisement
Answer
You can declare another generic parameter that takes the property name in at compile time.
JavaScript
1
5
1
export interface Requirement<R, N extends keyof R & string> {
2
name: N; // this will force the name property to be the same as being passed in
3
save(): R[N];
4
}
5
Then using it like this
JavaScript
1
5
1
const idRequirement: Requirement<PersonRequirements, "id"> ={
2
name: "id",
3
save: () => 0
4
}
5