我想创建一个请求映射,那就像一个api请求url配置,然后我可以很容易地像发送请求一样,sendRequest(name,body)。但这是打字稿中的语法错误吗?真奇怪
class HttpRequest {
baseURL = "http://localhost:8080" // get this by env later
requestMap = {
"city":{
method:"GET",
url: this.baseURL+"/area/city" ,
}
}
getRequest(requestName: String, body: object | null, params:null|object) {
return axios({
method:this.requestMap[String(requestName)]["method"],
url: this.requestMap[requestName]["url"] ,
params: params? params: null,
data:body? body:null
})
}
我想你得到这个错误:Type 'String' cannot be used as an index type
,对吗?
你得到这个错误是因为Typescript强迫你使用一个有效的类型来索引对象,requestMap
只有一个属性,叫做'city',当你尝试做this.requestMap[String(requestName)]["method"]
时,Typescript告诉你字符串不能索引requestMap,这是完全正确的,方法只存在于city
属性。
要解决这个问题,你可以做以下任何一件事:
或者将requestName参数的类型更改为'city':
class HttpRequest {
baseURL = "http://localhost:8080"; // get this by env later
requestMap = {
city: {
method: "GET",
url: this.baseURL + "/area/city",
},
};
getRequest(requestName: 'city', body: object | null, params: null | object) {
return axios({
method: this.requestMap[requestName]["method"],
url: this.requestMap[requestName]["url"],
params: params ? params : null,
data: body ? body : null,
});
}
}
或者,如果你想要一些灵活性,你可以创建一个包含requestMap
所有可能属性的类型,就像这样(当你确切知道对象可以拥有什么属性时):
type RequestProps = "city" | "country";
type RequestPropsType = {
method: string;
url: string;
};
class HttpRequest {
baseURL = "http://localhost:8080"; // get this by env later
requestMap: Record<RequestProps, RequestPropsType> = {
city: {
method: "GET",
url: this.baseURL + "/area/city",
},
country: {
method: "GET",
url: this.baseURL + "/area/country",
},
};
getRequest(
requestName: RequestProps,
body: object | null,
params: null | object
) {
return axios({
method: this.requestMap[requestName]["method"],
url: this.requestMap[requestName]["url"],
params: params ? params : null,
data: body ? body : null,
});
}
}
但是如果你想要充分的灵活性,使requestMap被任何字符串索引,你可以将string更改为string,但在这种情况下,不能保证属性将存在,所以你应该使用可选的链操作符(从typescript v3.7开始可用)来避免访问未定义的函数:
class HttpRequest {
baseURL = "http://localhost:8080"; // get this by env later
requestMap = {
city: {
method: "GET",
url: this.baseURL + "/area/city",
},
};
getRequest(
requestName: string,
body: object | null,
params: null | object
) {
return axios({
method: this.requestMap[requestName]?.["method"],
url: this.requestMap[requestName]?.["url"],
params: params ? params : null,
data: body ? body : null,
});
}
}