0

I'm trying declare a function type and then use that in a class, and in objects, and interfaces like this:

declare function IUpdateMode(mode: Mode): void;

Then I want to use it like this:

type Foo = {
   updateMode: IUpdateMode
}


class Foo extends React.Component<any> {

    updateRedMode(mode): IUpdateMode {}

}

function updateGreenMode(mode): IUpdateMode {

}

Is this possible in typescript?

0

1 Answer 1

1

I think what you really want is just this:

type UpdateMode = (mode: Mode) => void

Now you can use it anywhere as you mentioned, but with some corrections:

interface IFoo { // interface instead of a type is preferable when possible (e.g. you may extend it)
   updateMode: UpdateMode
}


class Foo extends React.Component<any> implements IFoo {

    updateMode = (mode: Mode) => {}

}

const updateGreenMode: UpdateMode = (mode) => { // there is no way to restrict a classic function to type alias or interface

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

3 Comments

Oh thank you! Is it not possible to use this with the function upgradeGreenMod() {} style?
You are welcome! No, it's not possible unfortunately, to restrict a classic function to some type alias or interface.
I've polished the answer a bit more. e.g. the (non-mandatory, for-convenience) convention is to add "I" character to the beginning of interfaces, not types. Also class should implement Ifoo interface

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.