我有一个看起来像这样的 ts 类型
class ImageServices {
services: SERVICE;
constructor(services: SERVICE) {
// creating key-value pair, key -> name of service, value api key (easy to access)
this.services = { ...services };
}
服务接口在哪里
export interface SERVICE {
unsplash?: string;
pexels?: string;
pixabay?: string;
shutterstock?: SHUTTERSTOCK_INIT;
}
和 SHUTTERSTOCK_INIT
就是这个
export interface SHUTTERSTOCK_INIT {
consumer_id: string;
consumer_secret: string;
}
现在,在我的类函数中,我正在这样做
async getSpecificServiceData(inputParams: QUERY_PARAMS, service: SERVICENAME): Promise<IMAGE_RESPONSE> {
const clientId = this.services[service]
if (!clientId) throw new Error(`Client ID does not exist for service ${service}`)
if (
service === "unsplash" &&
canMakeApiRequest(unsplash_allowed_props, inputParams)
) {
return await this.getDataFromUnsplash(clientId, inputParams);
} else if (
service === "pexels" &&
canMakeApiRequest(Pexels, inputParams)
)
} else if (service === "shutterstock" && typeof clientId === 'object') {
return await this.getDataFromShutterStock(clientId, inputParams);
}
{
return await this.getDataFromPexels(clientId, inputParams);
else {
throw new Error('Service Passed does not exist or problem with input params')
}
}
这里是SERVICENAME
export type SERVICENAME = "unsplash" | "pexels" | "pixabay" | "shutterstock";
这里出现以下错误
Argument of type 'string | SHUTTERSTOCK_INIT' is not assignable to parameter of type 'string'.
Type 'SHUTTERSTOCK_INIT' is not assignable to type 'string'.
和
Type 'string' is not assignable to type 'SHUTTERSTOCK_INIT'
我可以使用 ts-ignore,但无论如何要在不使用 ts-ignore 和 typeof 的情况下解决这些问题,即 typeof clientId === 'object'
用于快门库存而 typeof clientId === 'string'
用于其他?
这些行
await this.getDataFromPexels(clientId, inputParams);
和return await this.getDataFromShutterStock(clientId, inputParams);
对于 getDataFromPexels
和其他服务,clientId 类型为 string
,仅对于 getDataFromShutterStock
,clientId 类型为 SHUTTERSTOCK_INIT