Nishant Baranwal
Nishant Baranwal

Reputation: 1248

Typescript Generic type not assignable error

Trying to create a generic but it's showing error: Type "User[]" is not assignable to type T[] not able to understand what is wrong in doing this-

interface User {
    name: string,
    age: number
}

interface Movie {
    title: string,
    language: string
}

function getItems<T>(arg: number|string): T[] {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a: User[] = getItems<User>('user_list');

Upvotes: 0

Views: 239

Answers (2)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250366

The problem is that your function is not really generic. When using a generic parameter, you can't return a specific type, you need to respect the generic parameter that was passed to you. A function signature that would do what you want would be one using overloads

function getItems(arg: string): User[] 
function getItems(arg: number): Movie []  
function getItems(arg: number|string): User[] | Movie []  {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
         return useList;
    } else {
         return movieList;
   }
}

Upvotes: 2

Tao
Tao

Reputation: 2240

You should use function overloads for your case instead of generics.

Note that the signature of the function with the implementation will be hidden by the compiler.

function getItems(arg: string): User[];
function getItems(arg: number): Movie[];
function getItems(arg: number | string) {
    let useList: User[] = [];
    let movieList: Movie[] = [];
    if (typeof arg == 'string') {
        return useList;
    } else {
        return movieList;
    }
}

var a = getItems('user_list');

Upvotes: 2

Related Questions