TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

T | (() => T)

Open dhmk083 opened this issue 6 years ago • 33 comments

TypeScript Version: 3.9.0 (Nightly)

Search Terms: T | (() => T), T & Function

Code

type Initializer<T> = T | (() => T)
// type Initializer<T> = T extends any ? (T | (() => T)) : never

function correct<T>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg // error
}

Line 2 provides a workaround for this. More info on stackoverflow.

Expected behavior: no errors

Actual behavior: This expression is not callable. Not all constituents of type '(() => T) | (T & Function)' are callable. Type 'T & Function' has no call signatures.

Playground Link: here.

Related Issues: none

dhmk083 avatar Mar 28 '20 13:03 dhmk083

This check isn't safe if T is instantiated with something like (x: string) => number.

DanielRosenwasser avatar Mar 29 '20 09:03 DanielRosenwasser

@DanielRosenwasser Why does the following alternative work then?

type Initializer<T> = T extends any ? (T | (() => T)) : never

function correct<T>(arg: Initializer<T>): T {
    return typeof arg === 'function' ? arg() : arg // arg is callable in the true branch
}

Playground

arg becomes Initializer<T> & Function in the true branch and is callable. This example seems quite similar to me with the only difference, that Initializer<T> from OP is a union function type, above not. We could ask the same question here: is the check for T safe?

In addition, I expected Function to be a very generous type. Today you already can do invocations with all sorts of arguments:

declare const foo: Function
// all compile
foo()
foo(3)
foo("bar",3, true)

So I would expect and wish that behavior at least gets consistent. Either for both examples, a) an error should be emitted or b) both should compile to be in line with the current Function type behavior.

Appreciate your thoughts, thanks!

bela53 avatar Mar 29 '20 10:03 bela53

@bela53

const r2 = correct<(_: string) => number>((v: string) => v.toString().length)

this code passes type validation but blows in runtime.

zerkms avatar Mar 29 '20 10:03 zerkms

@zerkms Good catch. You could fix that error by choosing a more narrow type relationship test in Initializer<T> conditional type:

type Initializer<T> = T extends () => any ? (T | (() => T)) :
    T extends Function ? never : (T | (() => T))
const r3 = correct<(_: string) => number>((v: string) => v.toString().length) // error

However, this isn't directly related to the main issue. typeof arg === 'function' will only be able to narrow to Function in the true branch, and in principle you can invoke Function with any arguments.

The question remains, if both Initializer<T> & Function (currently works) and (() => T) | (T & Function) (currently doesn't work) are callable or not. Only one or the other would be inconsistent in my view.

bela53 avatar Mar 29 '20 12:03 bela53

that seems like a bug

DanielRosenwasser avatar Mar 29 '20 19:03 DanielRosenwasser

Simplified.

function f<T>(arg: T & Function) {
    typeof arg === 'function' && arg(); // `T & Function` is callable.
}
function g<T>(arg: T | (() => T)) {
    typeof arg === 'function' && arg(); // Type 'T & Function' has no call signatures.(2349)
}

falsandtru avatar Mar 30 '20 08:03 falsandtru

@bela53

type Initializer<T> = T extends Function ? never : (T | (() => T))

Seems to be working too and is shorter. I think I will use this typing.

By the way,

type Initializer<T> = T | (() => T)
// -or-
type Initializer<T> = T extends any ? (T | (() => T)) : never

const isFunction = (arg: any): arg is Function => typeof arg === 'function'

function correct_2<T>(arg: Initializer<T>): T {
    return isFunction(arg) ? arg() : arg
}

const x = correct_2<() => number>(() => 5)
// x: () => number

This compiles, but produces a mismatch between type and runtime value.

dhmk083 avatar Mar 30 '20 16:03 dhmk083

Unfortunately, this typing doesn't always work. I've found some inconsistencies in its behavior:

// type Initializer<T> = T | (() => T)
// -or-
type Initializer<T> = T extends Function ? never : T | (() => T)

function f_1<T>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg
}

function f_2<T extends number>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg
}

function f_3<T>(arg: Initializer<Partial<T>>) {
    return typeof arg === 'function' ? arg() : arg
}

function f_4<T>(arg: Initializer<Record<'a', T>>) {
    return typeof arg === 'function' ? arg() : arg
}

Playground

If you try with line 1 typing, it will fail f_1 case as expected, but it will also work for cases 2,3,4. If you try with line 3, it will fail for cases 2 and 3. I don't get why it doesn't work for Partial, but works for Record<K, T>. I think they should either all work or all fail.

dhmk083 avatar Mar 30 '20 18:03 dhmk083

@falsandtru well summarized the issue. I would add one case:

// if you set a constraint for T, it works again (?)
function g2<T extends number>(arg: T | (() => T)) {
    typeof arg === 'function' && arg(); // () => T is callable.
}

Plagyround with all three examples

@dhmk083 Your example seems to describe a different issue related to (unresolved) conditional types. Not sure why f_2 and f_3 aren't handled properly.

bela53 avatar Mar 31 '20 09:03 bela53

@bela53 In your last example T extends number means that T is definitely not a Function, so it works. If you replace it with T extends object constraint, it will produce an error, because Function extends object, too.

Here is another simplified case:

// OK
function g<T>(arg: T extends Function ? never : (T | (() => T))) {
    typeof arg === 'function' && arg(); // () => T is callable.
}

// error
function g2<T extends object>(arg: T extends Function ? never : (T | (() => T))) {
    typeof arg === 'function' && arg(); // () => T is callable.
}

Adding a constraint breaks things.

dhmk083 avatar Mar 31 '20 10:03 dhmk083

Is this related #27422?

jack-williams avatar Apr 06 '20 21:04 jack-williams

Ran into this while trying to use the SetStateAction<T> type in react:

type SetStateAction<S> = S | ((prevState: S) => S);

If using typeof foobar === 'function' isn't the correct way to check whether we have a value, or a callable initializer function, what is?

Svish avatar Jan 06 '21 10:01 Svish

Found that this reveals the issue:

function a<T>(b: T | (() => T)) {
  return typeof b === 'function' ? b() : b
}

But this does not (and compiles file):

function a<T>(b: T | (() => T)) {
  return b instanceof Function ? b() : b
}

Kind of odd, because typeof checks seem to work normally. But this is a reasonable workaround for anyone who bumps into it. HT to @pbteja1998 :)

NOTE: this workaround can have problems in some situations: https://github.com/microsoft/TypeScript/issues/37663#issuecomment-856866935 Check a safer (though more verbose) workaround: https://github.com/microsoft/TypeScript/issues/37663#issuecomment-856961045)

kentcdodds avatar Jan 13 '21 20:01 kentcdodds

FYI: instanceof workaround doesn't work for values in generic Record

type Schema = {
    id: string;
    type: string;
}

type Config = {
    schema: Schema | (() => Schema)
}

function f<T extends Record<string, Config>>(config: T, key: string) {
    if (config[key] instanceof Function) {
        config[key]() // This expression is not callable
    }
}

Playground

Found that this reveals the issue:

function a<T>(b: T | (() => T)) {
  return typeof b === 'function' ? b() : b
}

But this does not (and compiles file):

function a<T>(b: T | (() => T)) {
  return b instanceof Function ? b() : b
}

Kind of odd, because typeof checks seem to work normally. But this is a reasonable workaround for anyone who bumps into it. HT to @pbteja1998 :)

misha-erm avatar May 17 '21 13:05 misha-erm

Be careful with using x instanceof Function (as suggested by @kentcdodds), as it won't be reliable in cases where the value comes from a different context (e.g. iframe/window/realm). Objects (including functions) from other contexts will have a different Function constructor in their prototype chain than the one being used to perform the check.

jsejcksn avatar Jun 08 '21 15:06 jsejcksn

True, I should have mentioned that (I've definitely bumped into this issue in the past and it was very confusing at the time 😅). I'd love a solution rather than a workaround :)

kentcdodds avatar Jun 08 '21 15:06 kentcdodds

Here's one that feels a little verbose, but seems to work:

type Fn = (...args: unknown[]) => unknown;

function getValue <
  Provided,
  T = Provided extends Fn ? ReturnType<Provided> : Provided,
>(valueOrFn: Provided): T {
  return typeof valueOrFn === 'function' ? valueOrFn() : valueOrFn;
}

Playground

jsejcksn avatar Jun 08 '21 17:06 jsejcksn

So basically at this point, the only way to make this work is to use instanceof??

You know, I could have sworn this method of using typeof foo === 'function', used to work! In fact I just started noticing it in VSCode today.

Was this a regression?

It also doesn't seem to affect eslint...just weird


Aha! I knew I wasn't crazy! It seems this error only appears when I allow vscode to use the version of typescript which it comes bundled with: 4.6.0-dev.20220124. Once I switch to the typescript version installed locally (4.5.5), the error disappears.

Possible reason...

Most likely cause is that some feature in the development versions of typescript is not included in the later stable versions, and that is what has been triggering this same error since 2020. From 3.9 nightly till 4.6 nightly

smac89 avatar Jan 25 '22 18:01 smac89

This is the only reasonable way I could find around this without having to cast all the things as <shape of function>:

const isFunction = (x: unknown): x is Function => typeof x === 'function'

Here's an example of it in action with a nice cond function I've been working on

rpearce avatar Feb 28 '22 03:02 rpearce

I've been using this type guard recently, and it also seems to solve the problem. It would be nice to have a fix, though!

declare type AnyFunction = (...args: unknown[]) => unknown

function isFunction<T extends AnyFunction>(value: unknown): value is T {
  return typeof value === 'function'
}

Elia-Darwish avatar Mar 29 '22 08:03 Elia-Darwish