[英]Typescript: function that returns a predefined union type
Is there a way in TypeScript to model a function that can return an already specified union type, like myFunc
in the example below? TypeScript 到 model 中是否有一种方法可以返回已经指定的联合类型,例如下面示例中的
myFunc
?
type UnionType = {
field: "one",
value: "two"
} | {
field: "a" | "b",
value: "a1" | "b1" | "c1"
}
myFunc("one", "two") // OK
myFunc("a", "a1") // OK
myFunc("a", "b1") // OK
myFunc("b", "a1") // OK
myFunc("one", "a1") // ERROR: only allowed second argument should be "two"
myFunc("one", "a") // ERROR: only allowed second argument should be "two"
myFunc("a", "two") // ERROR: only allowed second argument should be "a1" or "b1" or "c1"
A first naive approach might be something like this:第一种天真的方法可能是这样的:
const myFunc = <T extends UnionType>(field: T["field"], value: T["value"]): UnionType => ({
field,
value,
})
Which doesn't compile because the arguments are not dependent.哪个不编译,因为 arguments 不依赖。 Somehow I need
value
to be constrained by the type of field
.不知何故,我需要
value
受field
类型的约束。
Thanks谢谢
type InferValue<T extends UnionType, K extends UnionType["field"]> =
// Use `extends` keyword to limit, refer to TypeScript `Exclude` implementation
T extends (
// get the matching struct, but it cannot be used directly
{
field: K;
value: any;
} extends T
? T
: never
)
? T["value"]
: never;
const myFunc = <K extends UnionType["field"]>(
field: K,
value: InferValue<UnionType, K>
): any => ({ // any
field,
value,
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.