Let’s say I have the following type:
interface MyType {
myProperty: [a: string[], b: string[]]
}
and now I want to create an array out of that type:
const array1: MyType[] = [
{myProperty: [["Hello", "World"], []]},
{myProperty: [["Hello"], []]},
];
If I try to sort that array:
const array2: MyType[] = [
{myProperty: [["Hello", "World"], []]},
{myProperty: [["Hello"], []]},
].sort((a,b) => a.myProperty[0].length - b.myProperty[0].length);
I get an error:
Type '{ myProperty: string[][]; }[]' is not assignable to type 'MyType[]'.
I tried various workarounds:
-
Array initialization with sort (lambda)
const array2: MyType[] = [ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ].sort((a,b) => a.myProperty[0].length - b.myProperty[0].length);
Value doesn’t have correct type
-
Array initialization with sort (function)
const array3: MyType[] = [ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ].sort(compareMyType); function compareMyType(a: MyType, b: MyType) { return a.myProperty[0].length - b.myProperty[0].length; }
Sort function doesn’t have correct type and value doesn’t have correct type
-
Casting to
MyType[]
:const array4: MyType[] = ([ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ] as MyType[]).sort(compareMyType); const array5: MyType[] = ([ {myProperty: [["Hello", "World"], []]}, {myProperty: 5}, ] as MyType[]).sort(compareMyType);
Casting supresses errors which can cause runtime errors
-
Sorting already initialized array
const array1: MyType[] = [ const array2: MyType[] = [ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ]; const array6: MyType[] = array1.sort(compareMyType);
No errors.
Why is this working, while the other attempts are not (compiler or runtime errors)? Are there better/other workarounds?
Playground
1