简体   繁体   中英

Can typescript not infer the type of unique symbol passed directly into a function?

I'm trying to make a utility like ts-action<\/code> but with symbol<\/code> as action type instead of string<\/code> .

When symbol is passed directly into the function, typescript fails to infer the type. Is there something I do not know?

interface Action<T extends symbol> {
    type: T;
}

function action<T extends symbol>(type: T): () => Action<T> {
    return () => ({ type });
}

const SOME_ACTION_TYPE = Symbol('some action type');
const actionBuilder = action(SOME_ACTION_TYPE);
type actionBuilderType = typeof actionBuilder;
// expected: () => Action<typeof SOME_ACTION_TYPE>
// actual: () => Action<typeof SOME_ACTION_TYPE>

const actionBuilder2 = action(Symbol('another action type'));
type actionBuilder2Type = typeof actionBuilder2
// expected: () => Action<typeof Symbol('another action type')>
// actual: () => Action<symbol>

This is because 'another action type'<\/code> in Symbol('another action type')<\/code> is not being infered, because Symbol<\/code> constructor is not parametrized, I mean it does not have generic parameter.

interface SymbolConstructor {
    /**
     * A reference to the prototype.
     */
    readonly prototype: Symbol;

    /**
     * Returns a new unique Symbol value.
     * @param  description Description of the new Symbol object.
     */
    (description?: string | number): symbol;

    /**
     * Returns a Symbol object from the global symbol registry matching the given key if found.
     * Otherwise, returns a new symbol with this key.
     * @param key key to search for.
     */
    for(key: string): symbol;

    /**
     * Returns a key from the global symbol registry matching the given Symbol if found.
     * Otherwise, returns a undefined.
     * @param sym Symbol to find the key for.
     */
    keyFor(sym: symbol): string | undefined;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM