0

In the following, I would expect this to fail as I've stated afternoon should be of type number, but it doesn't fail.

My guess is I'm destructuring incorrectly as hovering over the word afternoon when it returns shows the type as any (in VS Code).

Alternatively, it could all be wrong, this is literally my first play with Typescript, not getting it, yet!

const greetings =  {
    morning: "Good morning.",
    evening: "Good evening.",
    afternoon: "Good afternoon.",
};

interface AboutGreetingTypes {
    morning: string,
    evening: string,
    afternoon: number,
};

const aboutGreeting = ({copy}): AboutGreetingTypes => {
    const d = new Date();
    const timeInHours = d.getHours();

    const { morning, evening, afternoon } = copy;

    if (timeInHours < 12) {
        return morning;
    }
    if (timeInHours > 18) {
        return evening;
    }
    if (timeInHours > 12) {
        return afternoon;
    }
};

console.log(aboutGreeting({copy: greetings}));

2
  • It looks like afternoon has the wrong type? afternoon: "Good afternoon.", vs: afternoon: number, in the interface does not match. I don't get how copy got into the mix. Commented May 2, 2022 at 17:21
  • You'll want to spend some dedicated time reading through the TypeScript handbook. Here's a link to getting started for JS programmers. Commented May 2, 2022 at 18:58

2 Answers 2

2

Your function parameter type should be {copy: AboutGreetingTypes} not just AboutGreetingTypes

Sign up to request clarification or add additional context in comments.

1 Comment

Not sure what you mean by that.
1
const aboutGreeting = ({copy}): AboutGreetingTypes => {

This line declares a function that accepts a single untyped object and returns an AboutGreetingTypes. Since the argument has no declared type, it is assumed to be any, which lets you do anything without without a type error.


What I think you want is a function that accepts an object that has a copy property that has value of an AboutGreetingTypes.

That would look like this:

const aboutGreeting = ({ copy }: { copy: AboutGreetingTypes }) => {

See playground which still has some errors, but those resolving those are answers to different questions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.