Home > Back-end >  Define type for date component in typescript
Define type for date component in typescript

Time:06-18

Since I am new to typescript , can you please suggest me how can i define type for my date component (separator='')

export function getCurrentDate(separator=''){

  let newDate = new Date()
  let date = newDate.getDate();
  let month = newDate.getMonth()   1;
  let year = newDate.getFullYear();
  
  return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
  }

CodePudding user response:

Thats how you define this function in typescript

export function getCurrentDate(separator: string = ''): string{

  let newDate = new Date()
  let date = newDate.getDate();
  let month = newDate.getMonth()   1;
  let year = newDate.getFullYear();
  
  return `${year}${separator}${month<10?`0${month}`:`${month}`}${separator}${date}`
  }

You can omit the type definition of the separator, typescript will automatically bind a type string to the separator since it has a default value of a string in an operation known as type inference, you can read more about type inference here

  • Related