英文:
Typescript Interface Add Unknown Dynamic variables
问题
以下是已翻译的内容:
我想定义一个接口,其中包含一些已知变量和一些其他动态变量。
假设这是接口的定义:
export interface ApplicationData {
applicant?: ApplicantData;
application_unit?: ApplicationUnit;
interested_people_count?: number | undefined;
}
我该如何在这个接口中定义以下内容:
interested_person_1: InterestedPerson;
interested_person_3: InterestedPerson;
expenses_1q_2023: Expenses;
expenses_3q_2022: Expenses;
因此,我事先不知道这些变量会有多少,我只知道如果以'interested_person_'开头,那么它就是InterestedPerson接口,如果以'expenses_'开头,那么它就是Expenses接口。
英文:
I'd like to define a interface that has some known variables and some other dynamic.
Let's assume this definition of interface:
export interface ApplicationData {
applicant?: ApplicantData;
application_unit?: ApplicationUnit;
interested_people_count?: number | undefined;
}
How would I define that in this interface could also be:
interested_person_1: InterestedPerson;
interested_person_3: InterestedPerson;
expenses_1q_2023: Expenses;
expenses_3q_2022: Expenses;
So I do not know in advance how many these variables will be there, only what I know is that if it starts with 'interested_person_' then it is InterestedPerson interface and if it starts with 'expenses_' then it is Expenses interface.
答案1
得分: 3
我们需要定义两个索引签名,一个用于感兴趣的人,另一个用于费用。为了定义这些键,我们将使用模板字符串。
示例:
type StartsWithInterest = `interest_${string}`
这个类型将处理所有以interest_
开头的字符串,对于编译器来说,其余部分不重要:
const ok: StartsWithInterest = 'interest_correct'
const notOk: StartsWithInterest = 'incorrect' // 预期错误
我们可以将模板字符串应用于我们的索引签名,这将给我们所需的结果:
type GenericType = {
[x: `interested_person_${string}`]: InterestedPerson;
[x: `expenses_${string}`]: Expenses;
};
英文:
We need to define two index signatures, one for interested persons and the other one for expenses. To define the keys we are going to use template strings.
Example:
type StartsWithInterest = `interest_${string}`
This type will handle all strings that start with interest_
and the rest of it doesn't matter for the compiler:
const ok: StartsWithInterest = 'interest_correct'
const notOk: StartsWithInterest = 'incorrect' //expected error
We can apply the template string to our index signatures that will give us the desired result:
type GenericType = {
[x: `interested_person_${string}`]: InterestedPerson;
[x: `expenses_${string}`]: Expenses;
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论