Sorry if this question is too stupid :D
I have an interface
:
interface APIRoutes {
SIGNUP : string,
LOGIN : string,
}
And a const
, like routes config
.
const APIs: APIRoutes = {
SIGNUP : Config.baseURL "/signup",
LOGIN : Config.baseURL "/login",
}
I want to declare a function
, it will take one of those route as parameter
:
const callAPI = async (APIRoute: string, body: any, headers: any) => {
//...
}
The problem is, I don't know how to make this function only accept one of the APIRoutes
properties.
I mean something like this:
callAPI(APIs.SIGNUP, ...) // => OK
callAPI(APIs.STACKOVERFLOWISAWESOME, ...) // => ERROR
How can I do this? Not only interface, whatever can solve this problem is great.
Thanks
CodePudding user response:
You need keyof
operator. It takes an object type and produces a union of its keys.
interface APIRoutes {
SIGNUP : string,
LOGIN : string,
}
const APIs: APIRoutes = {
SIGNUP : "/signup",
LOGIN : "/login",
}
const callAPI = async (APIRoute: keyof APIRoutes) => {
}
console.log(callAPI('asdasd'));
console.log(callAPI('SIGNUP'));
console.log(callAPI('LOGIN'));