reactjstypescriptnext.jstimeago

TypeScript, Library:React-Time-Ago thinks it requires a number, I'm giving it a string. I cant figure out how to make it accept a number?


       import ReactTimeAgo from "react-time-ago"

        <ReactTimeAgo 
        
          date = {tweet._createdAt}
          />

_createdAt outputs time as 2022-06-02T01:16:40Z

I'm using React-time-ago to change it into like 21 minutes ago. It actually works fine. Yet, TypeScript complains staying that date parameter needs to come in as a number. so i went into the index.d.ts and changed the type from number to any.

interface Props extends React.HTMLAttributes<HTMLElement> {
    date: Date | any;
    future?: boolean;
    timeStyle?: string | Style;
    round?: string;
    minTimeLeft?: number;
    tooltip?: boolean;
    component?: React.ReactType;
    wrapperComponent?: React.ReactType;
    wrapperProps?: object;
    locale?: string;
    locales?: string[];
    formatVerboseDate?: (date: Date) => string;
    verboseDateFormat?: object;

That stopped the error for vscode, but it still shows up on the browser and my deployment fails because of that error. How do I get typescript to stop complaining about getting a string?

This is the error https://i.sstatic.net/b85pA.jpg


Solution

  • First of all, you shouldn't try to change the library files manually.

    The date property in this package accepts a union type of Date and number. So your best bet would be to convert the date string into a Date object before feeding the date property field. You can use a method like;

    const creationDate: Date = new Date('2022-06-02T01:16:40Z')
    

    To parse that date string into a date object and then give it as a prop.

    By editing your direct example;

    import ReactTimeAgo from "react-time-ago"
    
    <ReactTimeAgo 
      date = {new Date(tweet._createdAt)}
    />