2

I have an abstract class with a Generic that I implement with a Union type such as :

export abstract class DAO<T> { 
  async getDocument(ref: string): Promise<T> {
        // irrelevant code that return T asynchronously
  }
}

export class ConfigurationDAO extends DAO<ConfigurationType> {
 //...
}

export type ConfigurationType = 'advertising' | 'theming';

The getDocument() signature for the ConfigurationDAO class is then :

async getDocument(ref: string): Promise<ConfigurationType>

The problem is that when I call this function, I have an error :

const advertisingDocument: 'advertising' = await this.getDocument('advertising');

the error :

Type 'ConfigurationType' is not assignable to type '"advertising"'.
  Type '"theming"' is not assignable to type '"advertising"'

I don't understand why the 'advertising' type is not valid when the return type is 'advertising' | 'theming'

Aion
  • 620
  • 1
  • 6
  • 25
  • 1
    Explanation of why that doesn't work, as well as possible solutions: https://stackoverflow.com/a/51101237/197472 – Duderino9000 Aug 27 '21 at 00:31
  • Thanks for sharing. I found a solution in that indeed. I finally assigned by typecasting the `getDocument()` function : `const advertisingDocument: 'advertising' = await this.getDocument('advertising') as 'advertising';` Thanks a lot – Aion Aug 27 '21 at 07:48

1 Answers1

0

Typescript automatically types your advertisingDocument as ConfigurationType and you are trying to force-type it differently.
Think of it as if it was basic types.
For typescript you are basically doing the same as:

const test: number = 'name';

Being that 'name' is a string it isn't assignable to test which I declared as a number.

Hope it helped.

ryok90
  • 92
  • 2
  • Thanks for the explanation ! The answer of @Barryman9000 helped me to found a solution to this – Aion Aug 27 '21 at 07:49