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 cropped up for me today, after updating to v4.6.x from v4.5.5. I'd love to know what exactly changed between these two versions that broke my code. From the above, nobody has really figured out what the root cause might be. If the difference is so simply described (and by that I do not mean so simple a problem) in https://github.com/microsoft/TypeScript/issues/37663#issuecomment-605846042, what's the hold up on a triage here?

WoodyWoodsta avatar May 23 '22 13:05 WoodyWoodsta

@WoodyWoodsta this bug is fully triaged. What do you mean?

RyanCavanaugh avatar May 26 '22 22:05 RyanCavanaugh

@RyanCavanaugh Might be a difference in our understanding on what "triage" means :) Not sure how the backlog milestone is treated for this project but given this was identified and added to that backlog two years ago, I was wondering if there was anything holding it back given it has now clearly found its way into stable release.

WoodyWoodsta avatar May 27 '22 05:05 WoodyWoodsta

i think maybe typeof == 'function' cannot exclude unknown type?

type Initializer<T> = T | (() => T)
function correct<T>(arg: Initializer<T>) {
    return typeof arg === 'object' && typeof arg == "function" ? arg() : arg // no error
}

type NoUnknown = number|string|never;
function correct2<T extends NoUnknown>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg // no error
}

type withUnknown = number|string|never|unknown;
function correct3<T extends withUnknown>(arg: Initializer<T>) {
    return typeof arg === 'function' ? arg() : arg // same error
}

keyboard3 avatar Jun 09 '22 01:06 keyboard3

I gave up and just casted it.

// global.d.ts
type Fn<TArgs extends ReadonlyArray<any>=unknown[], TRet=unknown> = (...args: TArgs[]) => TRet
type AnyFn = Fn<any[],any>

// resolvable.ts
export type Resolvable<T = any, TArgs extends ReadonlyArray<any> = []> = T | ((...args: TArgs) => T)

export type Resolved<T> = T extends Fn ? ReturnType<T> : T

export function resolveValue<T, TArgs extends ReadonlyArray<any>>(val: Resolvable<T, TArgs>, ...args: TArgs): T {
    return typeof val === 'function' ? (val as AnyFn)(...args) : val
}

mnpenner avatar Dec 20 '22 08:12 mnpenner

I don't think this is a bug. You use typeof arg to identify whether the arg is a function, but from the perspective of the TS compiler, arg may not be a function as you declared T | (() => T). The TS compiler doesn't know what your code does, therefore it is not safe to call arg()

pspdragon avatar Feb 18 '23 03:02 pspdragon

I think a safer approach would be to let the developer decide what is or isn't type T using a function that uses a type predicate

function someFuncName<T>(arg: T | (() => T), isTypeT: (val: unknown) => val is T): T {
    if (isTypeT(arg)) {
        return arg;
    }
    return arg();
}

EltonLobo07 avatar Aug 05 '23 09:08 EltonLobo07

Got more workarounds! lol. Like @EltonLobo07 mentioned, I'm using a predicate to get the job done. But for my code base, the following is sufficient for me to work around the issue.

type MyUnion<T> = T | ((arg: string) => T);

function doMyLogic<S>(arg: MyUnion<S>): void {
  const stringArg = "my-string";

  // @ts-expect-error -- Weird TypeScript Bug
  const value = typeof arg === "function" ? arg(stringArg) : arg;
  const betterValue = isFunction(arg) ? arg(stringArg) : arg; // Success
}

function isFunction(value: unknown): value is (arg: string) => unknown {
  return typeof value === "function";
}

This is obviously not reliable for broad usage. But since I needed a quick TS fix and the impact was minimal, I reached for this. Less verbosity. The narrowed type in the doMyLogic function uses the correct return value (rather than unknown).

ITenthusiasm avatar Aug 14 '23 13:08 ITenthusiasm

This works fine? Or maybe I missed the point...?

export type ValueTFn<T = any> = T extends ((...args: unknown[]) => unknown) ? never : T | (() => T);
export namespace ValueTFn {
  export function get<T = any>(valueOrFn: ValueTFn<T>): T {
    return typeof valueOrFn === "function" ? valueOrFn() : valueOrFn;
  }
}

Compiles, runs, and returns what I expect from:

let a1 = 1;
let a2 = () => 2;
let a3 = (foo: any) => foo;
let a4 = null;
let a5 = "Hello!";
let a6 = () => a1;

console.log(ValueTFn.get(a1)); // 1
console.log(ValueTFn.get(a2)); // 2
console.log(ValueTFn.get(a3)); // undefined
console.log(ValueTFn.get(a4)); // null
console.log(ValueTFn.get(a5)); // "Hello!"
a1 = 42;
console.log(ValueTFn.get(a6)); // 42

Playground

EDIT: Actually further testing exposed a different problem with the above: If I declare something as foo: ValueTFn<boolean> it's type resolves to boolean | () => false | () => true instead of the expected boolean | () => boolean ...which is a problem, because it means this doesn't compile:

let b: boolean;
func = () => { return b; };
foo: ValueTFn<boolean> = func;
// Error "Type '() => boolean' is not assignable to 'boolean | () => false | () => true'
//   Type '() => boolean' is not assignable to '() => false'
//      Type 'boolean' is not assignable to 'false'

Is that a different bug? Why does the compiler over-eagerly resolve <T = boolean> () => T as () => false | () => true?? It does so even if strict is off. Tested it on every Playground version from 3.3.3 to Nightly.

AnorZaken avatar Sep 14 '23 14:09 AnorZaken

I don't think this is a bug. You use typeof arg to identify whether the arg is a function, but from the perspective of the TS compiler, arg may not be a function as you declared T | (() => T). The TS compiler doesn't know what your code does, therefore it is not safe to call arg()

It knows there are only two types, type T or type () => T. T can be anything including a function, but the other type IS definitely a function. If you check the type with a typeof arg === 'function' then arg must be callable. It's definitely a bug given the arg is callable because it is a function. It could be considered that the error message is incorrect and that the message should be something like Type T could be a function that does not match the signature () => T, but that is against the intent of the developer at that point, because we don't have runtime checking of specific arguments etc. How would be go about describing that T can be anything, including a function, but that if it matches a specific call signature and return value, then it should execute some other code?

I think the intent of the developer here is to have T be something other than a function, but if it IS a function it should return T. If I pass () => something that is not T to the function as arg, the TS compiler should error at that point.

function doMyThing <T>(arg: T | () => T): T {
    if (typeof arg === "function") { // This should be enough to indicate that arg() is callable
        // This should not error
        return arg();
    }

    return arg;
}
// This should error
doMyThing<boolean>(() => "hello");

Irrelon avatar Nov 27 '23 13:11 Irrelon

Sorry for commenting on an old thread, but TS 5.5, there is inferred type guards, making the following code valid:

const isFunction = (x: unknown) => typeof x === "function";

export const correct = <T,>(initialValue: T | (() => T)) => {
  return isFunction(initialValue) ? initialValue() : initialValue;
};

where initialValue is correctly inferred as () => T if it is a function, and T otherwise. IMO, this is a little better than writing it out the output as T is Function since it would sync with the function implementation.

jeremy-code avatar May 25 '24 02:05 jeremy-code

It's true that T could also be a function, but i also agree that typeof "function" should already narrow it down. There's 3 solutions in the Playground Link, the second one is weird but it works. Hope it helps!

type Action<T> = T | ((p: T) => T);

let state: any;

// 1
const setState = <T,>(value: Action<T>) => {
  state = value instanceof Function ? value(state) : value;
};

// 2
type NotAFunction = string ...

Playground Link

joaorr3 avatar Nov 15 '24 13:11 joaorr3

Conditional types can be used to eliminate passing Functions with a signature different from () => R:

function f<T>(v: T extends Function ? (T extends () => any ? T : never) : T) {
    return typeof v === "function" ? v() : v;
}

Unfortunately this leads to f having any return type. We could apply the following return type to the f:

T extends Function ? (T extends () => infer R ? R : never) : T

Though it emits an error (works in v.5.7.3, but not later). It can be worked around via type assertions, not ideal but it works. The final solution:

function f<T>(v: T extends Function ? (T extends () => any ? T : never) : T) {
    return (typeof v === "function" ? v() : v) as
        T extends Function ? (T extends () => infer R ? R : never) : T;
}

A few examples:

f("foo"); // => "foo"
f(() => "bar"); // => "bar"
f(() => 42); // => 42
f({}); // => {}
f((x: string) => x); // error

Moreover it even prevents the following case (which was mentioned in this SO thread):

type G = (x: string) => string;
const g: G = x => x.toUpperCase();
f<G>(g); // error

Playground


The solution above is actually a variation of this one posted on SO. It's even shorter:

function f<T>(v: T extends Function ? never : T | (() => T)) {
    return (typeof v === "function" ? v() : v) as T;
}

Playground

In v5.7.3 and earlier it can be written as:

function f<T>(v: T extends Function ? never : T | (() => T)): T {
    return typeof v === "function" ? v() : v;
}

Playground

WPMGPRoSToTeMa avatar Jul 18 '25 14:07 WPMGPRoSToTeMa