对不起,如果这个问题太愚蠢:D
我有一个interface
:
interface APIRoutes {
SIGNUP : string,
LOGIN : string,
}
和一个const
,如routes config
。
const APIs: APIRoutes = {
SIGNUP : Config.baseURL + "/signup",
LOGIN : Config.baseURL + "/login",
}
我想声明一个function
,它将使用其中一个路由作为parameter
:
const callAPI = async (APIRoute: string, body: any, headers: any) => {
//...
}
问题是,我不知道如何使这个函数只接受APIRoutes
属性之一。
我的意思是这样的:
callAPI(APIs.SIGNUP, ...) // => OK
callAPI(APIs.STACKOVERFLOWISAWESOME, ...) // => ERROR
我该怎么做?不仅是接口,只要能解决这个问题,那就太好了。
感谢您需要keyof
操作符。它接受一个对象类型,并产生它的键的联合。
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'));
链接