N
N
Ne7Le4Der2021-10-15 14:12:54
typescript
Ne7Le4Der, 2021-10-15 14:12:54

How to write a TypeScript function?

let a: string[] | CustomClass[];

    test(a);

   function test(data: string[]) {
        //Some code
   }


Argument of type 'string[] | 'CustomClass[]' is not assignable to parameter of type 'string[]'.


I need a function to be executed with string[] , and the passed argument simply returned with CustomClass[] . Tried to do an overload, but couldn't do it right.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-10-15
@Ne7Le4Der

Something like this can be done:

type TestResult<T extends string[] | CustomClass[]> = T extends CustomClass[] ? T : void;
function test<T extends string[] | CustomClass[]>(data: T): TestResult<T> {
    if (data[0] instanceof CustomClass) {
      return data as TestResult<T>;
    }

    return undefined as TestResult<T>;
}

https://www.typescriptlang.org/play?#code/CYUwxgNg...
But you can't do without type casting inside. Well, as WbICHA wrote in the comments, such types are not safe for an empty array, since there are no types in runtime, which means there is no way to check what type an empty array came in.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question