Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

fixing typescript string and object bug

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...