Dan Rasmuson
Dan Rasmuson

Reputation: 6023

Typescript: Typing if a parameter contains a field

I have the below function I'm trying to type without using any.

export function byMostRecent(arr: any[]) {
  return [...arr].sort((a,b) => {
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  })
}

I'm not sure how to say, "the parameter must contain a createdAt field".

Upvotes: 0

Views: 799

Answers (2)

kimobrian254
kimobrian254

Reputation: 577

You can use a createdAt type:

interface Dates {
  createdAt: string|number|Date
}
export function byMostRecent(arr: Dates[]) {
  return [...arr].sort((a,b) => {
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  })
}

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249666

You should use an interface (or as I will use below an anonymous type) and generics to constrain the argument type and to flow type information from argument to result:

export function byMostRecent<T extends { createdAt: string|number|Date }>(arr: T[]):T[] {
  return [...arr].sort((a,b) => {
    return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
  })
} 

Upvotes: 3

Related Questions