Home > database >  Cannot use namespace 'API' as a value
Cannot use namespace 'API' as a value

Time:03-13

I define the LoginResult in typescript like this:

declare namespace API {
  type LoginResult = {
    status?: string;
    type?: string;
    currentAuthority?: string;
  };
}

the response is another entity, so I want to transform the response to LoginResult, this is the code looks like:

export async function login(body: API.LoginParams, options?: { [key: string]: any }) {
  let loginResult = await request<API.ApiResponse>('/manage/admin/user/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    data: body,
    ...(options || {}),
  });
  let result = new API.LoginResult();


  return loginResult;
}

but the compiler shows that:

Cannot use namespace 'API' as a value.ts(2708)

what should I do to fix it? and transform the original ApiResponse to LoginResult? this is my ApiResponse define:

  type ApiResponse = {
    result?:any,
    msg?: string,
    resultCode?: string,
    statusCode?: string
  };

The ApiResponse and LoginResult are total different, I think the cast will not work.

CodePudding user response:

You need to use type casting. Most TypeScript types (excluding a few things like enums) do not translate to runtime as they are used for compile time type checking. So, you don't instantiate the type, you merely cast the runtime variable (in your case loginResult) to the type you need to cast it to.

return loginResult as API.LoginResult;

Now, that said, since request is generic, you could do that there without casting it first to API.ApiResponse.

return request<API.LoginResult>
  • Related