ember-cli / ember-ajax

Service for making AJAX requests in Ember applications
MIT License
212 stars 87 forks source link

Cannot set `namespace` in TypeScript subclass #393

Open Bouke opened 6 years ago

Bouke commented 6 years ago

I'm extending the AjaxService in TypeScript like this:

# services/ajax.ts
import AjaxService from 'ember-ajax/services/ajax';

export default class Ajax extends AjaxService {
    namespace = '/api';
}

Which gives the following compilation error:

app/services/ajax.ts(8,5): error TS2416: Property 'namespace' in type 'Ajax' is not assignable to the same property in base type '{ contentType: string; headers: undefined; host: undefined; namespace: undefined; trustedHosts: undefined; request<T = any>(url: string, options?: AJAXOptions): AJAXPromise<T>; raw<T = any>(url: string, options?: AJAXOptions): AJAXPromise<...>; ... 27 more ...; normalizeErrorResponse(_status: number, _headers: Heade...'.
  Type 'string' is not assignable to type 'undefined'.

In the source the value of namespace is defined as undefined: https://github.com/ember-cli/ember-ajax/blob/f5d32454d519364e65ed566b50768e00a1d8d4d4/addon/mixins/ajax-request.ts#L229

This means it doesn't accept a value of string. To allow this, the type definition needs to look like this:

namespace: undefined | string,

There's a few additional instances like this (headers, host, trustedHosts) and possibly more.

alexlafroscia commented 6 years ago

Thanks for the report! I'll definitely look into this

alexlafroscia commented 6 years ago

@pepke41 and I have been looking into this some and plan to fix it in a coming release.

The namespace: undefined | string, example you provided didn't work from us.

https://www.typescriptlang.org/play/index.html#src=const%20object%20%3D%20%7B%0D%0A%20%20%20%20foo%3A%20undefined%20%7C%20string%0D%0A%7D%3B

But I think we can use the unknown type (or maybe the as keyword?) to solve the problem instead.

phil294 commented 5 years ago

This looks fixed. Isnt it?

James-Byrne commented 5 years ago

Just ran into this issue today. I'm currently getting the same error with headers & trustedHosts. I'm defining them like:

@computed()
get trustedHosts() {
  return [/\.somedomain/];
}

get headers() {
  const headers: Headers = {
    Accept: 'application/vnd.api+json',
    'Content-Type': 'application/vnd.api+json',
  };

  // ...

  return headers;
}

I've added the different return types combinations above and my own types but I still see the same error.

Bouke commented 4 years ago

This has been fixed in https://github.com/ember-cli/ember-ajax/commit/2e2b0c517ea560ff92599f040b7f6d6c1f1282f9, but hasn't been released yet.

jonchay commented 3 years ago

I'm experiencing this problem as well. Is it possible to publish the fix?