Pri*_*war 5 javascript generics typescript type-annotation typescript-generics
我试图创建一个带有两个参数的函数,第一个是联合类型,第二个是取决于第一个参数类型的类型。
例如:
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K extends T>(fruit1: T, fruit2: K) {
// When execution reaches here
// both fruit1 and fruit2 need to be the same fruit
}
Run Code Online (Sandbox Code Playgroud)
现在,这些语句按预期工作
// Gives error since Orange is not same as Apple neither banana
doubleFruit("Orange", "Apple");
doubleFruit("Orange", "Banana");
// Runs peacefully, since both are same fruit
doubleFruit("Apple", "Apple");
Run Code Online (Sandbox Code Playgroud)
但是当第一个参数是动态的时候,奇怪的事情发生了
function run(x: "Orange" | "Apple") {
// Should not work, since x could be anything
doubleFruit(x, "Orange");
}
Run Code Online (Sandbox Code Playgroud)
我假设因为x可以是Orange或Apple,所以第二个参数Orange不遵循两个参数相同的标准。
编辑:这就是我想要实现的目标
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K extends T>(fruit1: T, fruit2: K) {
// When execution reaches here
// both fruit1 and fruit2 need to be the same fruit
}
function run(x: "Orange" | "Apple") {
// I need this to work:
// Whatever be the value of x, the other parameter would be equivalent,
// hence should be allowed
doubleFruit(x, x);
// But not these:
// since x could be anything, specifically sending one of
// values shouldn't work
doubleFruit(x, "Orange")
doubleFruit(x, "Apple")
}
Run Code Online (Sandbox Code Playgroud)
我需要一种方法来满足上述行为。
小智 0
请尝试这是否适合您的情况:
type Fruit = "Orange" | "Apple" | "Banana";
function doubleFruit<T extends Fruit, K>(fruit1: T, fruit2: K & T) {
// When execution reaches here
// both fruit1 and fruit2 need to be the same fruit
}
doubleFruit("Orange", "Apple");
doubleFruit("Orange", "Banana");
doubleFruit("Apple", "Apple");
const x: "Orange" | "Apple" = "Apple";
doubleFruit(x, "Orange");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99 次 |
| 最近记录: |