#Type for function with specified parameters but unspecified return type

13 messages · Page 1 of 1 (latest)

subtle bramble
#
fluid coralBOT
#

@subtle bramble Here's a shortened URL of your playground link! You can remove the full link from your message.

zaceno#7945

Preview:```ts
type NumFunc = (x: number) => any

const a:NumFunc = (x) => x > 5
const b:NumFunc = (x) => [...Array(x).keys()].join(',')
const c:NumFunc = (x) => x * 2

const A = a(3) //typescript infers that A is "any". How to make it understand it is "boolean"?
const B = b(4) //typescript infers that B is "any". How to make it understand it is "string"?
...```

vernal spade
#

just don't write a manual type for it

fluid coralBOT
#
That_Guy977#5882

Preview:```ts
type NumFunc = (x: number) => unknown

const a = ((x) => x > 5) satisfies NumFunc
// ^?
const b = ((x) => [...Array(x).keys()].join(',')) satisfies NumFunc
// ^?
const c = ((x) => x * 2) satisfies NumFunc
// ^?

const A = a(3) //typescript infers that A is "any". How to make it understand it is "boolean"?
...```

vapid spire
#

also works with any, but don't use any if avoidable

vernal spade
#

yeah that's a better way

subtle bramble
#

satisfies huh. Haven't encountered that keyword before. Is that new? Gonna go read up

vapid spire
#

it's pretty new yeah

subtle bramble
#

Cool cool cool. Thanks!

#

First paragraph of the docs for satisfies:

TypeScript developers are often faced with a dilemma: we want to ensure that some expression matches some type, but also want to keep the most specific type of that expression for inference purposes

#

That is a better, more general wording of precisely the issue I am having.

#

So new, and it already works in JSDoc as well. Brilliant

subtle bramble
#

forgot: !resolved