简体   繁体   English

如何让 TypeScript 根据返回值识别函数参数的类型?

[英]How do I make TypeScript recognize the type of an argument to a function based on the return?

function isType(
    value: any,
    type: 'undefined'|'object'|'boolean'|'number'|'bigint'|'string'|'symbol'|'function'
): boolean {
    return typeof value === type;
}

function getDefaultIfUndefined<T>(value: T|undefined, defaultValue: T): T
{
    return isType(value, 'undefined') ? defaultValue : value;
}

TypeScript complains that the return type of getDefaultIfUndefined() is T|undefined not just T. But it will always be T because the ternary ensures "defaultValue" will be returned if "value" is undefined. TypeScript 抱怨 getDefaultIfUndefined() 的返回类型是 T|undefined 而不仅仅是 T。但它始终是 T,因为如果“value”未定义,则三元确保将返回“defaultValue”。

TypeScript has no problem when it is written like this though:像这样写时,TypeScript 没有问题:

function getDefaultIfUndefined<T>(value: T|undefined, defaultValue: T): T
{
    return typeof value === 'undefined' ? defaultValue : value;
}

I have it!我有! That wasn't easy, look:这并不容易,看看:

interface TypeMap {
    undefined: undefined;
    object: object;
    boolean: boolean;
    number: number;
    bigint: bigint;
    string: string;
    symbol: symbol;
    function: (...args: any[]) => any;
}
function isType<T extends keyof TypeMap>(
    value: any,
    type: T 
): value is TypeMap[T] {
    return typeof value === type;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建一个泛型 typescript 类型 function 并从参数类型推断出返回类型? - How do I make a generic typescript type function that has the return type inferred from the argument type? 在TypeScript中,如何根据其参数之一的返回类型来确定函数的返回类型? - In TypeScript, how do I make a function's return type based on the return type of one of its arguments? Typescript:如何根据参数类型获取 function 的返回类型? - Typescript: How can I get return type of function based on argument type? 我如何让 typescript 根据 function2E977777777777777777777777777777777777777777777777777777777777777777777777777777777777BED18 的返回类型 functionC17A94F14Z 的返回类型来推断 function 的返回类型 - How do I get typescript to infer the return type of a function based on the return type on a function of its arguments Typescript function 基于参数的返回类型 - Typescript function return type based on argument 如何根据 Typescript 中的参数控制返回类型? - How can I control the return type based on an argument in Typescript? TypeScript:如何根据 function 参数类型设置 function 返回值类型 - TypeScript: How to set function return value type based on function argument type 基于参数的 Typescript 返回类型,类型不是函数重载 - Typescript return type based on argument with types not function overloading typescript:根据回调返回类型验证函数参数 - typescript: validate function argument based on callback return type 根据 TypeScript 中的 function 的参数确定返回类型 - Determine the return type based upon the argument of a function in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM