简体   繁体   English

TypeScript - 如何将一个 function 参数与另一个相关联?

[英]TypeScript - How to correlate one function parameter with another?

Let's imagine I have the following function that will create something using a template (tpl) and the template's params (params):假设我有以下 function 将使用模板 (tpl) 和模板的参数 (params) 创建一些东西:

create(tpl, params) {
  // create something
}

I have 2 templates, so I will use an enum to define it:我有 2 个模板,所以我将使用一个枚举来定义它:

enum TEMPLATE {
  TPL1 = "TPL1",
  TPL2 = "TPL2",
}

And each of those templates have a set of parameters: some params are common to both templates, some params are specific:这些模板中的每一个都有一组参数:一些参数对两个模板都是通用的,一些参数是特定的:

interface BaseParamsTPL {
  name: string;
  topic: string;
}

interface ParamsTPL1 extends BaseParamsTPL {
  URL: string;
}

interface ParamsTPL2 extends BaseParamsTPL {
  productId: number;
  price: number;
}

Now, what I want is my "create" function to have "linked" parameters, meaning that if I pass TEMPLATE.TPL1, I want the "params" object to match "ParamsTPL1", and same for TPL2.现在,我想要的是我的“创建”function 具有“链接”参数,这意味着如果我通过 TEMPLATE.TPL1,我希望“参数”object 匹配“ParamsTPL1”,对于 TPL2 也是如此。 So, something like the following should fail:所以,类似以下的事情应该失败:

const myCreation = create(TEMPLATE.TPL2, {
  name: "something",
  topic: "random",
  URL: "http://loin.labas.com"
}) // should fail because the "tpl" passed in doesn't match the "params" object.

I was thinking of something like that:我在想这样的事情:

create<T extends keyof typeof TEMPLATE>(tpl: T, params: `Params${T}`) {
  // create something
}

But it doesn't seems to be the good way of doing it.但这似乎不是这样做的好方法。

Any idea how I can achieve that?知道如何实现吗?

Function overloading will do this: Function 过载会这样做:

enum TEMPLATE {
    TPL2,
    TPL1
}

interface BaseParamsTPL {
  name: string;
  topic: string;
}

interface ParamsTPL1 extends BaseParamsTPL {
  URL: string;
}

interface ParamsTPL2 extends BaseParamsTPL {
  productId: number;
  price: number;
}

function create(template: TEMPLATE.TPL1, options: ParamsTPL1): any;
function create(template: TEMPLATE.TPL2, options: ParamsTPL2): any;
function create(template: TEMPLATE, options: any): any {

}


// TS transpiler won't allow this because of the typing in our function overload
const myCreation = create(TEMPLATE.TPL2, {
  name: "something",
  topic: "random",
  URL: "http://loin.labas.com"
})

const myCreation2 = create(TEMPLATE.TPL1, {
  name: "something",
  topic: "random",
  URL: "http://loin.labas.com"
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM