【发布时间】:2021-09-10 04:50:05
【问题描述】:
我想添加一个类型实用程序,它有条件地应该添加T。
见Codesandbox
思路如下:
类似这样的:type IfType<If, Eq, T>
-
If是string literal的一种类型,例如"Cat" | "Dog"。 -
Eq是If的提取字符串文字,例如"Cat"或"Dog" -
T是我想要返回的类型,如果传递的generic type是那个特定的类型。
T 扩展了一个object,但如果Eq 不是equal 则返回Partial<T>,因此该类型仍然知道object 键(用于解构)。
类似这样的:
util.ts
type IfType<
If extends string,
Eq extends If,
T extends object
> = If extends Extract<If, Eq> ? T : Partial<T>
otherfile.ts
type Type = 'read' | 'write';
type Props<T extends Type> = {
type: T
} & (
IfType<
T,
// This gets the ts(2344) error, and I don't know how to stop it
"write",
{ descriptionOnlyForWrite: string }
>
| IfType<
T,
// This gets the ts(2344) error, and I don't know how to stop it
"read",
{ hasRead: boolean}
>);
这给出了这个错误:
Type '"write"' does not satisfy the constraint 'T'.
'"write"' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Type'.
关于如何输入 helper util 类型有什么建议吗?
额外信息:我通常如何在没有 utils 类型的情况下键入它,它可以按我的意愿工作
type Type = 'read' | 'write';
type Props<T extends Type> = {
type: T;
} & (
| (T extends 'write' ? { descriptionOnlyForWrite: string } : { descriptionOnlyForWrite?: undefined })
| (T extends 'read' ? { hasRead: boolean } : { hasRead?: undefined })
);
【问题讨论】:
-
请提供更多您期望和不期望的示例
标签: typescript typescript-generics string-literals type-constraints