I have a ts type which looks like this
class ImageServices {
services: SERVICE;
constructor(services: SERVICE) {
// creating key-value pair, key -> name of service, value api key (easy to access)
this.services = { ...services };
}
Where Service inerface would be
export interface SERVICE {
unsplash?: string;
pexels?: string;
pixabay?: string;
shutterstock?: SHUTTERSTOCK_INIT;
}
and SHUTTERSTOCK_INIT
would be this
export interface SHUTTERSTOCK_INIT {
consumer_id: string;
consumer_secret: string;
}
Now, Inside my class function I am doing this
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')
}
}
Here SERVICENAME
is
export type SERVICENAME = "unsplash" | "pexels" | "pixabay" | "shutterstock";
Error
Here I am getting following error
Argument of type 'string | SHUTTERSTOCK_INIT' is not assignable to parameter of type 'string'.
Type 'SHUTTERSTOCK_INIT' is not assignable to type 'string'.
and
Type 'string' is not assignable to type 'SHUTTERSTOCK_INIT'
I can use ts-ignore, but anyway to solve these without using ts-ignore and typeof i.e typeof clientId === 'object'
for shutterstock and typeof clientId === 'string'
for others?
Update
These lines
await this.getDataFromPexels(clientId, inputParams);
and return await this.getDataFromShutterStock(clientId, inputParams);
for getDataFromPexels
and other service, clientId type is string
and only for getDataFromShutterStock
, clientId type is SHUTTERSTOCK_INIT
question from:
https://stackoverflow.com/questions/65841252/fixing-typescript-string-and-object-bug