[英]Defining concrete types for a generic component
我正在键入构建一个输入组件,该组件基本上是一个select
用于我的应用程序中的枚举,然后为一系列单行中的具体类型定义它们。 但无论我尝试什么,我似乎都会遇到打字问题。 我得到的最接近的是:
import React from 'react';
type Props<T> = {
enumType: T;
value?: keyof T;
};
type IEnumInput<T = {}> = React.FC<Props<T>>;
const EnumInput: IEnumInput = ({ enumType, value }) => {
const options = Object.values(enumType).map((x: any) => x.toString());
return (
<div>
Will select from {options.join(',')}, current value is {value}
</div>
);
};
type CProps<T> = {
value?: keyof T;
};
enum MyEnum {
A = 'a',
B = 'b',
C = 'c',
}
const MyEnumInput = (props: React.PropsWithChildren<CProps<MyEnum>>) =>
EnumInput({ ...props, enumType: MyEnum });
我得到的错误是
Type '{ enumType: typeof MyEnum; value?: number | "big" | "link" | "small" | "sub" | "sup" | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | ... 35 more ... | undefined; children?: React.ReactNode; }' is not assignable to type 'Props<{}>'. Types of property 'value' are incompatible.
Type 'number | "big" | "link" | "small" | "sub" | "sup" | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | ... 32 more ... | undefined' is not assignable to type 'undefined'.
Type 'number' is not assignable to type 'undefined'.
这是正确的方法吗?如果是,我做错了什么?
TLDR;
使用typeof MyEnum
代替MyEnum
。
长答案:
您将 enum 作为值与 enum 作为类型混淆了。
当您访问MyEnum.A
时,您将其用作一个值,在转译的 js 中是一个普通的 object,然后访问其属性“.A”。
当您将MyEnum
称为类型时,您实际上指的是该键值结构的值部分,在您的情况下是字符串文字'a' | 'b' | 'c'
'a' | 'b' | 'c'
'a' | 'b' | 'c'
。
如果要获取普通的 object MyEnum
的类型,则需要使用typeof MyEnum
。
附带说明一下,TS 中的 class 也发生了同样的事情。
当声明class Dog {}
时, Dog
既是类型又是值。
当将Dog
称为类型时,它是此 class 实例的类型。 当将Dog
称为值时,它是Dog
class 本身,也就是构造函数 function,而不是实例。
现在如果要获取Dog
构造函数 function 的类型,则需要使用typeof Dog
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.