【发布时间】:2021-03-12 22:50:17
【问题描述】:
我有一个反应组件,我正在向它传递一个泛型。基于这个泛型,我想更改回调负载类型。
在下面的示例中,我传递的 RelationType 可以是“one”或“many”,基于此,回调应该是字符串或字符串数组。
import React from 'react';
export enum RelationType {
one = 'one',
many = 'many',
}
interface Props<R extends RelationType> {
callback(newValue?: R extends RelationType.one ? string : string[]): void;
relationType: R;
}
export const Component = <R extends RelationType>({ onUpdate, relationType }: Props<R>) => {
return (
<button onClick={() => {
if (relationType === RelationType.one) {
callback('foo'); // TS2345: Argument of type '"foo"' is not assignable to parameter of type '(R extends RelationType.one ? string : string[]) | undefined'.
} else {
callback(['foo', 'bar']); // TS2345: Argument of type 'string[]' is not assignable to parameter of type 'R extends RelationType.one ? string : string[]'.
}
}}/>
)
};
Typescript 可以做到这一点吗?
【问题讨论】:
标签: reactjs typescript