[英]Typescript: Discriminated Union with value in function parameter resolves to 'any'
Both of these examples fail to see the type of the parameter in onSelect
... TS claims value
is any
if clearable
is not provided.这两个示例都看不到onSelect
中的参数类型...如果未提供clearable
,TS 声明value
是any
。
I'm at a loss.我不知所措。 I've attempted both with and without a generic: no dice.我尝试过使用和不使用泛型:没有骰子。 Any help?有什么帮助吗?
import React from 'react';
interface RequiredProps {
value: string;
clearable?: false;
onSelect: (value: string) => void;
}
interface ClearableProps {
value: string | null;
clearable?: true;
onSelect: (value: string | null) => void;
}
const Select: React.FC<ClearableProps | RequiredProps> = ({ value, clearable, onSelect }) => {
return <div />;
}
const Clearable = <Select value="abc" onSelect={(value) => { }} clearable={true} />;
const ExplicitNotClearable = <Select value="abc" onSelect={(value) => { }} clearable={false} />;
// Why doesn't TS know `value` is a `string`, but rather thinks this function has no type?
const NotClearable = <Select value="abc" onSelect={(value) => { }} />;
import React from 'react';
interface Props<T> {
clearable?: boolean;
onSelect: (value: T) => void;
value: T;
}
interface RequiredProps extends Props<string> {
clearable?: false;
}
type ClearableType = string | null;
interface ClearableProps extends Props<ClearableType> {
clearable: true;
}
const Select: React.FC<ClearableProps | RequiredProps> = ({ value, clearable, onSelect }) => {
return <div />;
}
const Clearable = <Select value="abc" onSelect={(value) => { }} clearable={true} />;
const ExplicitNotClearable = <Select value="abc" onSelect={(value) => { }} clearable={false} />;
// Why doesn't TS know `value` is a `string`, but rather thinks this function has no type?
const NotClearable = <Select value="abc" onSelect={(value) => { }} />;
I'm a little confused because in your two cases, clearable
is either optional or required in ClearableProps
.我有点困惑,因为在您的两种情况下, clearable
在ClearableProps
中是可选的或必需的。 I expect you mean it to be required in both versions, right?我希望您的意思是在两个版本中都需要它,对吗? Anyway, I will assume that.无论如何,我会假设。
This looks like a known bug, microsoft/TypeScript#31618 .这看起来像一个已知的错误, microsoft/TypeScript#31618 。 The value
callback parameter is not being contextually typed when the callback is assigned to a union-typed onSelect
property.当回调分配给联合类型的onSelect
属性时, value
回调参数不是上下文类型的。 When you explicitly discriminate the union by setting clearable
the problem goes away.当您通过设置clearable
明确区分联合时,问题就消失了。
This issue is on the backlog, so it's not likely to be addressed anytime soon.此问题已积压,因此不太可能很快得到解决。
You can work around this by explicity annotating the type of value
:您可以通过显式注释value
的类型来解决此问题:
const ImplicitlyNotClearable = <Select value="abc" onSelect={(value: string) => { }} />;
which isn't the best, but it least it's something.这不是最好的,但至少它是一些东西。
Okay, hope that helps;好的,希望有帮助; good luck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.