expect-type icon indicating copy to clipboard operation
expect-type copied to clipboard

.map fn

Open mmkal opened this issue 1 year ago • 2 comments

@aryaemami59 another potential helper that occurred to me might be useful. I'm not totally convinced it's worth it, but thought I'd open a draft PR in case you had thoughts. Given .toBeCallableWith doesn't work well for generic functions, it's a catch-all way to say "I am allowed to do this with my object" and make assertions on the result, without actually calling the function or performing side-effects, etc.:

const capitalize = <S extends string>(input: S) =>
  (input.slice(0, 1).toUpperCase() + input.slice(1)) as Capitalize<S>

expectTypeOf(capitalize)
  .map(fn => fn('hello world'))
  .toEqualTypeOf<'Hello world'>()

But the assertion could just as easily (maybe more easily) be written as:

expectTypeOf(() => capitalize('hello world')).returns.toEqualTypeOf<'Hello world'>()

Which also doesn't actually call capitalize at runtime.

Advantages of .map:

  • it makes it clearer it's an asertion about capitalize rather than an inline callback.
  • it works fine with expectTypeOf<X>() as well as expectTypeOf(x)
  • implementation is v simple so the cost is low

It could also sub in for how we do .toBeCallableWith in #83 too:

type Factorize = {
  (input: number): number[]
  (input: bigint): bigint[]
}

expectTypeOf<Factorize>().map(f => f(12)).toEqualTypeOf<number[]>()
expectTypeOf<Factorize>().map(f => f(12n)).toEqualTypeOf<bigint[]>()

mmkal avatar Aug 12 '24 13:08 mmkal

Not sure about this one yet, I'd say let's get #83 in first then we can use this one to potentially fill in any left over gaps.

aryaemami59 avatar Aug 13 '24 05:08 aryaemami59

Open in Stackblitz

npm i https://pkg.pr.new/mmkal/expect-type@98

commit: 1850004

pkg-pr-new[bot] avatar Aug 13 '24 09:08 pkg-pr-new[bot]

@aryaemami59 I keep forgetting this is still a draft. Not a particularly exciting feature but v small implementation cost and somewhat useful so I'd like to get it in. Let me know if you have any thoughts on the code.

mmkal avatar Feb 13 '25 10:02 mmkal