简体   繁体   English

在 Typescript 中,如何指定可以返回多种类型的函数的返回类型?

[英]In Typescript, how can I specify the return type of a function that can return multiple types?

I have a reusable method getFilters that can return a number of different types我有一个可重用的方法getFilters可以返回许多不同类型

getFilters(): IListFilteringType {...}
type IListFilteringTypeMultiSelect = (string | number)[];
type IListFilteringType = boolean | string | number | IListFilteringTypeMultiSelect;

When I call getFilters how can I specify that I know that the returned value with be of type IListFilteringTypeMultiSelect and not one of the other possible values of IListFilteringType ?当我打电话getFilters我怎么可以指定我知道,与返回的值是类型的IListFilteringTypeMultiSelect ,而不是其他的可能值之一IListFilteringType

Thank you谢谢

如果您确定特定执行的函数返回的类型,则可以使用as返回值。

const variable = functionResponse as IListFilteringTypeMultiSelect;

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

相关问题 将 object 传递给 function 时,如何指定 TypeScript 类型? - How can I specify a TypeScript type when passing an object into a function? 我是否需要在 javascript/typescript 中为匿名函数指定返回类型? - Do I need to specify a return type for an anonymous function in javascript / typescript? 如何从 TypeScript 函数返回一个类? - How can I return a class from a TypeScript function? 在Typescript中,Object.prototype函数可以返回Sub类型实例吗? - in Typescript, can Object.prototype function return Sub type instance? TypeScript:你能根据函数的参数定义一个返回类型结构吗? - TypeScript: Can you define a return Type structure based on an argument of the function? 如何在TypeScript中使用返回类型创建函数? - How to create a function with return types in TypeScript? 我可以将参数类型指定为多种类型之一而不是 TypeScript 中的任何类型吗? - Can I Specify Parameter Type as One of Many Types Instead of Any Type in TypeScript? TypeScript - 基于多个参数的函数返回类型 - TypeScript - Function return type based on multiple parameters flowtype:如何通过参数计数/类型重载函数返回类型? - flowtype: how can i overload function return types by argument count/types? 如何使用打字稿和节点从依赖项中指定类型? - How can I specify a type from a dependency with typescript and node?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM