[英]Typescript: optional method param based on type
I have a method where id is only available when it is of type B, look below我有一个方法,其中 id 仅在类型 B 时可用,请看下面
(index: string, type: ResourceType.A, data: any): JSX.Element;
and和
(index: string, type: ResourceType.B, data: any, id: string): JSX.Element;
So I tried to create a method overload as所以我试图创建一个方法重载
type IOverload = {
(index: string, type: ResourceType.A, data: any): JSX.Element;
(index: string, type: ResourceType.B, data: any, id: string): JSX.Element;
}
and now tried to create a method as现在尝试创建一个方法作为
const getJsx: IOverload = (
index: string,
type: ResourceType.A | ResourceType.B,
data: any,
id?: string
)=> {
.
.
.
type === ResourceType.B ? myFunc(id) : yourFunc(data)
}
and my method myFunc
is declared as我的方法
myFunc
被声明为
const myFunc = (id: string) => {
but now I get an error as shown below for myFunc
但现在我收到了如下所示的
myFunc
错误
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Please help to solve this, I would prefer making a change to getJsx
and don't want to declare my method myFunc
with string | undefined
请帮助解决这个问题,我更喜欢对
getJsx
进行更改,并且不想用string | undefined
声明我的方法myFunc
string | undefined
string | undefined
as string | undefined
为
const myFunc = (id: string| undefined) => {
You could create an overload which will throw an error if a resource is not of Resource.B
and there are 4 parameters ( Playground ):您可以创建一个重载,如果资源不是
Resource.B
并且有 4 个参数( Playground ),则会抛出错误:
enum ResourceType {
A, B
}
function test(index: string, type: ResourceType.B, data: any, id: string): any;
function test(index: string, type: ResourceType.A, data: any): any;
function test(...args: (string | ResourceType)[]) {
const index = args[0] as string
const type = args[1] as ResourceType
const data = args[2] as any
const id = args[3] as string | undefined
}
test('abc', ResourceType.A, 'myData', 'myId') // Throws error
test('abc', ResourceType.A, 'myData') // Accepted
test('abc', ResourceType.B, 'myData', 'myId') // Accepted
test('abc', ResourceType.B, 'myData') // Throws error
Typescript doesn't understand that id
is never undefined
in that situation, because the argument is declared as optional with ?
打字稿不明白在这种情况下
id
永远不会被undefined
,因为参数被声明为可选的?
. .
I don't know if it's possible to properly type your functions to work as you intend (I don't know how to do it), but a quick fix that would remove your error is to provide a default with nullish coalescing:我不知道是否可以正确键入您的函数以按您的意愿工作(我不知道该怎么做),但是可以消除您的错误的快速修复是提供具有无效合并的默认值:
type === ResourceType.B
? myFunc(id ?? '') // Here typescript is happy, because there is a string fallback if id is undefined
: yourFunc(data)
Simply do简单地做
myFunc(id as string)
And you problem is solved你的问题解决了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.