我有这个辅助函数,它在用 JavaScript 编写时运行良好。但是当我添加 TypeScript 时,奇怪的事情开始发生。那是一个带有函数的文件:
interface Toy {
setId: string;
name: string;
year: number;
themeId: number;
themeName: string;
subthemeId: number;
subthemeName: string;
parts: number;
imageUrl: string;
brandName: string;
}
enum SortBy {
NameAsc = 'name-asc',
NameDsc = 'name-dsc',
PartsAsc = 'parts-asc',
PartsDsc = 'parts-dsc',
YearAsc = 'year-asc',
YearDsc = 'year-dsc'
}
type Property = 'name' | 'parts' | 'year';
type Type = 'asc' | 'dsc';
type SortParams = [Property, Type];
const sortToys = (_toys: Toy[], sortBy: SortBy): any => {
const toys = _toys.sort((toy1, toy2) => {
const [property, type] = <SortParams>sortBy.split('-');
const properties = {
toy1: toy1[property],
toy2: toy2[property]
};
if (properties.toy1 > properties.toy2) {
return type === 'asc' ? 1 : -1;
} else if (properties.toy1 < properties.toy2) {
return type === 'asc' ? -1 : 1;
}
return 0;
});
const pages = [];
while (toys.length) {
pages.push(toys.splice(0, 30));
}
return pages;
};
export default sortToys;
这是我在尝试构建项目时遇到的错误:
src\utils\helpers\filterToys.ts
Line 12:11: Parsing error: Unexpected token, expected "}"
10 | const [property, type] = <SortParams>sortBy.split('-');
11 | const properties = {
> 12 | toy1: toy1[property],
| ^
13 | toy2: toy2[property]
14 | };
15 | if (
我知道对象本身没有问题,但可能发生了一些事情。我想不通,也许有人看到了一些奇怪的东西?
出现这个错误是因为 TS 不确定你是否使用 JSX。
只是尽量避免<Type>variable
符号。
如果要使用类型断言,只需使用as
运算符。
interface Toy {
setId: string;
name: string;
year: number;
themeId: number;
themeName: string;
subthemeId: number;
subthemeName: string;
parts: number;
imageUrl: string;
brandName: string;
}
enum SortBy {
NameAsc = 'name-asc',
NameDsc = 'name-dsc',
PartsAsc = 'parts-asc',
PartsDsc = 'parts-dsc',
YearAsc = 'year-asc',
YearDsc = 'year-dsc'
}
type Property = 'name' | 'parts' | 'year';
type Type = 'asc' | 'dsc';
type SortParams = [Property, Type];
const sortToys = (_toys: Toy[], sortBy: SortBy): any => {
const toys = _toys.sort((toy1, toy2) => {
const [property, type] = sortBy.split('-') as SortParams; // fixed
const properties = {
toy1: toy1[property],
toy2: toy2[property]
};
if (properties.toy1 > properties.toy2) {
return type === 'asc' ? 1 : -1;
} else if (properties.toy1 < properties.toy2) {
return type === 'asc' ? -1 : 1;
}
return 0;
});
const pages = [];
while (toys.length) {
pages.push(toys.splice(0, 30));
}
return pages;
};
export default sortToys;
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句