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'

2
  • 1
    Explanation of why that doesn't work, as well as possible solutions: stackoverflow.com/a/51101237/197472 Commented Aug 27, 2021 at 0: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 Commented Aug 27, 2021 at 7:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the explanation ! The answer of @Barryman9000 helped me to found a solution to this

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.