1

given a type like:

type SomeFunctionType = (arg: string) => string

it it possible to apply this type to a function within an object inline? Basically apply the type SomeFunction to someFunction below.

const someObject = {
  someFunction: (arg) => arg
}

The only ways I've found is either to have the function outside the object:

const someFunction: SomeFunctionType = (arg) => arg

const someObject = {
  someFunction
}

or to type the object:

const someObject: { someFunction: SomeFunctionType } = {
  someFunction: (arg) => arg
}

but it feels like there should be a shorter way.

1 Answer 1

2

Type casting any individual value is done with as.

const someObject = {
  someFunction: ((arg => arg) as SomeFunctionType)
}

Or fully type the function so it matches your intended type:

const someObject = {
  someFunction: (arg: string): string => arg
}

But most of the time you probably do want provide an interface at the object level. But it's hard to advise on that with only a contrived example.

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.