0

I want make a function, let it can be called like

addPets('Dog', someEvent);

there has problem on first parameter, I need force keyword, maybe a enum or type, but I don't know how do force that?

example:

export enum PetType {
    Cat  = 'Cat',
    Dog  = 'Dog',
    Fish = 'Fish'
}

addPets('Dog', someEvent); // fine
addPets('Cat', someEvent); // fine
addPets('Cow', someEvent); // error, because PetType not have Cow

thank every help.

5
  • Please clarify, do you want a type checking? Commented Dec 10, 2019 at 10:45
  • In my opinion, that parameter maybe don't need type checking Commented Dec 10, 2019 at 11:44
  • After all, this parameter is a default parameter and it is a string. If I use a type, I do n’t know how to implement it. Commented Dec 10, 2019 at 11:50
  • There is a jQuery example, .on ('click', ...), where the string 'click' is a valid value, while .on ('cow', ...) is not, similar to this. Commented Dec 10, 2019 at 11:53
  • You can create interface with string type but enum is more suitable here Commented Dec 10, 2019 at 13:12

1 Answer 1

2

You should declare the argument type in your function signature and invoke it using the PetType enum.

function addPets(petType: PetType, ...): void {
   ...
}

addPets(PetType.Cat, someEvent);
addPets(PetType.Dog, someEvent);
Sign up to request clarification or add additional context in comments.

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.