gpt4 book ai didi

javascript - Typescript 接口(interface)并创建该接口(interface)的对象

转载 作者:行者123 更新时间:2023-11-30 20:33:54 26 4
gpt4 key购买 nike

我正在用 typescript 创建一个小应用程序,我在其中使用接口(interface)创建特定类型的对象,如以下 UserProfile 接口(interface)。

interfacefulfill 函数都在user-profile.ts 文件中定义。

export interface UserProfile  {

readonly titel_id: number;
readonly user_name: string;
readonly email: string;
readonly first_name: string;
readonly last_name: string;
readonly phone: string;
readonly fax: string;

}

export function fulfill({ titel_id, user_name, email, first_name, last_name, phone, fax }: any): UserProfile {
return {

titel_id,
user_name,
email,
first_name,
last_name,
phone,
fax
}
}

我从我的 UserMdoel 的 find 函数中调用此函数,该函数包含用户表的所有字段,并且 fulfill 函数仅提供接口(interface)中指定的那些字段。但是正如您所看到的,我必须将这些字段写 3 次

一次在接口(interface)中,然后在对象解构中,然后在 return 语句中。这意味着如果我以后必须更改字段,我必须在 3 个地方更改它。

有没有更好的方法来解决这个问题?

最佳答案

我更新了我的答案。

接口(interface)在转换为 javascript 后无法存活。您可以做的一件事是创建一个包含所有名称的数组,并使用该数组自动复制所有字段。

不过,您仍然需要在两个地方维护字段。

export const USER_PROFILE_FIELDS: string[] = [
'titel_id',
'user_name',
'email',
'first_name',
'last_name',
'phone',
'fax',
];
export interface UserProfile {

readonly titel_id: number;
readonly user_name: string;
readonly email: string;
readonly first_name: string;
readonly last_name: string;
readonly phone: string;
readonly fax: string;

}

export function fulfill(template: any): UserProfile {
return <UserProfile>USER_PROFILE_FIELDS.reduce(
(object, key) => object[key] = template[key],
{}
);
}

如果您需要它用于多个接口(interface),您可以创建一个高阶函数来为您创建 fulfill 函数。这样您就不需要为每个案例手动创建一个 fulfill 函数。这是一个例子:

// This function accepts the fields you want to use and returns your fulfill function
export function createFullfill<ResultingType>(fields: string[]) {
return function(template: any) {
return <ResultingType>fields.reduce(
(object, key) => object[key] = template[key],
{}
);
}
}

// Fulfill function for UserProfile
export const fulfillUserProfile = createFullfill<UserProfile>(USER_PROFILE_FIELDS);
// Fulfill function for Project
export const fulfillProject = createFullfill<Project>(PROJECT_FIELDS);

关于javascript - Typescript 接口(interface)并创建该接口(interface)的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50038337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com