Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typescript version of this? #22

Open
m1thrandir225 opened this issue Jan 21, 2023 · 1 comment
Open

Typescript version of this? #22

m1thrandir225 opened this issue Jan 21, 2023 · 1 comment

Comments

@m1thrandir225
Copy link

Getting started with solid, and wanted to create something similar but I have been struggling to get the createAgent.js file converted to typescript.

My current problem is:
const headers = {},
body = {},
opts = { method, headers, body };
if (data !== undefined) {
headers["Content-Type"] = "application/json";
opts.body = JSON.stringify(data);
}
But, headers["Content-type"] has this error, which I don't know how to fix, as u can't exactly get the headers type from the fetch api.
Element implicitly has an 'any' type because expression of type '"Content-Type"' can't be used to index type '{}'.
Property 'Content-Type' does not exist on type '{}'.

I know is kinda dumb but any help would be appreciated

@SonyStone
Copy link

It should be something like this

type HttpMethod = "get" | "post" | "put" | "delete" | "patch";

async function send<T>(
  method: HttpMethod ,
  url: string,
  data?: any,
): Promise<T>
async function send<T>(
  method: HttpMethod ,
  url: string,
  data: any,
  resKey: keyof T
): Promise<T[typeof resKey]>
async function send<T>(
  method: HttpMethod ,
  url: string,
  data?: any,
  resKey?: any
): Promise<T> {
  const headers: HeadersInit = {};
  const opts: RequestInit = { method, headers };

  if (data !== undefined) {
    headers["Content-Type"] = "application/json";
    opts.body = JSON.stringify(data);
  }

  if (state.token) {
    headers["Authorization"] = `Token ${state.token}`;
  }

  try {
    const response = await fetch(API_ROOT + url, opts);
    const json: T = await response.json();

    return resKey ? json[resKey] : json;
  } catch (err) {
    if (err && err.response && err.response.status === 401) {
      actions.logout();
    }
    return err;
  }
}

You can try to use Chat Openai for such stuff. It works pretty well 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants