Typescript - 正确输入带有可选参数的函数

标签 typescript

假设我们有以下函数:

function test<S, T>(obj: S, prop: keyof S, mapper?: (value: S[keyof S]) => T): S[keyof S] | T {
  return typeof mapper === 'function'
    ? mapper(obj[prop])
    : obj[prop];
}

如果我在没有 mapper 参数的情况下使用它,则无法正确推导返回值的类型:

const value = test({ a: 'stringValue' }, 'a'); // value is of type "unknown"

但是如果我提供一个恒等函数作为第三个参数,它就会被正确推导:

const value = test({ a: 'stringValue' }, 'a', x => x); // value is of type "string"

test 函数应该如何输入,以便当我们不提供 mapper 参数时,可以正确推导返回值的类型?

Playground link

最佳答案

只需使用 function overloads !

function test<S, T>(obj: S, prop: keyof S): S[keyof S];
function test<S, T>(obj: S, prop: keyof S, mapper: (value: S[keyof S]) => T): T;
function test<S, T>(obj: S, prop: keyof S, mapper?: (value: S[keyof S]) => T): S[keyof S] | T {
    return typeof mapper === 'function'
        ? mapper(obj[prop])
        : obj[prop];
}

const value = test({ a: 'stringValue' }, 'a'); // string

const value2 = test({ a: 'stringValue' }, 'a', x => x);  // string

Playground

关于Typescript - 正确输入带有可选参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72927797/

相关文章:

javascript - 如何制作一种类型取决于参数

javascript - 在 JSDoc @typedef 中使用导入类型

typescript - 这个类型声明在 Typescript 中是什么意思?

javascript - Angular2组件的 "this"在执行回调函数时未定义

typescript - 类型 'assign' 上不存在属性 'ObjectConstructor'

reactjs - 在 react native + typescript 应用程序上运行 jest 时出错(Jest 遇到意外 token )

typescript - 管道 "|"符号导致 typescript 定义文件中出现错误

typescript - 定义类型以从类型的选定键中创建对象似乎已被破坏

typescript - 将两种类型关联在一起

javascript - typescript :Getter can't return array with custom type