简体   繁体   English

Typescript:输入带有可选参数的 function

[英]Typescript: Type a function with optional parameter

I am looking for typing functions with optional argument我正在寻找带有可选参数的类型函数

I tried this:我试过这个:

type MyFunctionType<T = null> = (options: T) => unknown;
const func1: MyFunctionType<{ option1: number }> = (options) => options.option1;
const func2: MyFunctionType = () => 'test';
console.log(func1({option1: 12})); // Ok
console.log(func2()); // Error : Expected 1 argument

typescript shows an error on func2. typescript 在 func2 上显示错误。


So i tried with "?"所以我试着用“?” on options parameter:关于选项参数:

type MyFunctionType2<T = null> = (options?: T) => unknown;
const func1: MyFunctionType2<{ option1: number }> =  (options) => options.option1;
const func2: MyFunctionType2 = () => 'test';
console.log(func2()); // Ok
console.log(func1()); // No error is raised

But in this case, typescript does not show error for using func1 without parameter.但在这种情况下,typescript 不显示使用不带参数的 func1 的错误。

Is there a way to solve this?有没有办法解决这个问题?

Thank you for reading感谢您阅读

Yes, using conditional types:是的,使用条件类型:

type MyFunctionType<T = null> = T extends null | undefined
    ? (options?: T) => unknown
    : (options: T) => unknown;

const func1: MyFunctionType<{ option1: number }> = (options) => options.option1;
const func2: MyFunctionType = () => 'test';

func2();
func1(); // shows an error "Expected 1 arguments, but got 0."

This defined the generic type MyFunctionType to be a function whose parameter is optional in case the type of the parameter is null, undefined or the union of both.这将泛型类型MyFunctionType定义为 function,如果参数的类型为 null、未定义或两者的联合,则其参数是可选的。 You could even leave them out entirely in this case:在这种情况下,您甚至可以将它们完全排除在外:

type MyFunctionType<T = null> = T extends null | undefined
    ? () => unknown
    : (options: T) => unknown;

Arguably though, I cannot really see a usecase for a type definition like this as it will always shadow the actual return type and force a single parameter while not allowing multiple ones which might help readability.不过,可以说,我真的看不到这样的类型定义的用例,因为它总是会隐藏实际的返回类型并强制使用单个参数,而不允许使用多个可能有助于提高可读性的参数。

Try this way type MyFunctionType<T = never> = (options: T) => unknown;试试这种方式类型 MyFunctionType<T = never> = (options: T) => unknown;

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

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