假设我有以下类型:
interface MyType {
myProperty: [a: string[], b: string[]]
}
现在我想创建一个该类型的数组:
const array1: MyType[] = [
{myProperty: [["Hello", "World"], []]},
{myProperty: [["Hello"], []]},
];
如果我try 对该数组进行排序:
const array2: MyType[] = [
{myProperty: [["Hello", "World"], []]},
{myProperty: [["Hello"], []]},
].sort((a,b) => a.myProperty[0].length - b.myProperty[0].length);
我得到一个错误:
Type '{ myProperty: string[][]; }[]' is not assignable to type 'MyType[]'.
我try 了各种解决方案:
-
使用排序初始化数组(Lambda)
const array2: MyType[] = [ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ].sort((a,b) => a.myProperty[0].length - b.myProperty[0].length);
值没有正确的类型
-
使用排序初始化数组(函数)
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; }
排序函数没有正确的类型并且值没有正确的类型
-
选角至
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);
铸造 suppress 可能导致运行时错误的错误
-
排序已初始化的数组
const array1: MyType[] = [ const array2: MyType[] = [ {myProperty: [["Hello", "World"], []]}, {myProperty: [["Hello"], []]}, ]; const array6: MyType[] = array1.sort(compareMyType);
没有错误.
为什么这有效,而其他try 却无效(编译器或运行时错误)?有更好的/其他解决方案吗?