0

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');
2
  • returning two array of different interface type is just for demo. I just want to make a generic function say I can pass some parameter and It should be able to return "any" type of data as expected. If I have to use function overloads then it is confusing to me what is the advantage of generic in typescript. As definition days make a method generic by adding <T> or something. Commented Feb 22, 2018 at 8:08
  • Also when i hover the function call it's showing return type correctly (as expected by mentioning <User>) Commented Feb 22, 2018 at 8:14

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

Comments

2

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;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.