tsconst sortBy = <T>(predicate: (a: T) => any = a => a) => (a: T, b: T) =>
predicate(a) > predicate(b) ? 1 : predicate(b) > predicate(a) ? -1 : 0;
any
をやめたい any
は、 T
型がObjectの場合は、その子要素の型 T
型がprimitive型の場合は、そのままts monitors.sort(sortBy(c => moment(c.publishStartAt)));
ts[5,4,3,2,1].sort(sortBy(c => 1))
tstype Values<T> = T extends { [key: string]: infer U } ? U : T;
const a = { hoge: 1, piyo: 'hoge', fuga: true } as const;
type A = Values<typeof a>; // 1|'hoge'|true
tsconst sortBy =
<T>(predicate: (a: T) => Values<T>) =>
(a: T, b: T) =>
predicate(a) > predicate(b) ? 1 : predicate(b) > predicate(a) ? -1 : 0;