如何通过指定每个属性及其值来实例化 TypeScript 中的对象?

问题描述 投票:0回答:3

这是我在服务中实例化一个新的

content
对象的片段:

const newContent = new Content(
     result.obj.name
     result.obj.user.firstName,
     result.obj._id,
     result.obj.user._id,
);

问题在于,这种对象实例化方式依赖于我的

content
模型中的属性顺序。我想知道是否有办法通过将每个属性映射到我想要设置的值来实现这一点,例如:

 const newContent = new Content(
     name: result.obj.name,
     user: result.obj.user.
     content_id: result.obj._id,
     user_id: result.obj.user._id,
 );
typescript syntax instance instantiation
3个回答
23
投票
const newContent = <Content>({
    name: result.obj.name,
    user: result.obj.user.
    content_id: result.obj._id,
    user_id: result.obj.user._id,
 });

在这里您可以实例化一个对象并使用类型断言或转换为内容类型。 有关类型断言的更多信息:https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions


12
投票

您可以将一个对象传递给包装所有这些变量的构造函数:

type ContentData = {
    name: string;
    user: string;
    content_id: string;
    user_id: string;
}

class Content {
    constructor(data: ContentData) {
        ...
    }
}

然后:

const newContent = new Content({
     name: result.obj.name,
     user: result.obj.user.
     content_id: result.obj._id,
     user_id: result.obj.user._id,
});

0
投票

来自 C# 背景,其中对象初始化器被认为是理所当然的,我也想看看是否可以在打字稿中实现类似的语法来初始化数据字段,而无需太多的重复/样板,这是我想出的代码:

type FunctionProp<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type Fields<T> = Omit<T, FunctionProp<T>>;
type PartialFields<T> = Partial<Fields<T>>;

class User {}
class Content {
    public name!: string;
    public user!: User; 
    public content_id!: string; 
    public user_id!: string;

    constructor(obj: Fields<Content>) { 
        for (const key of Object.keys(obj)) {
            (this as any)[key] = (obj as any)[key];
        }
    }

    print() { console.log(this.name); }
}

const content = new Content({
    name: "test",
    user: new User(),
    user_id: "USER-001",
    content_id: "CONTENT-001"
});
console.log(content);
// Output: Content {name: 'test', user: User, content_id: 'CONTENT-001', user_id: 'USER-001'}

在我看来,它使得初始化简单数据对象(DTO、POCO)更具可读性并且不易出错。可以在构造函数中使用

PartialFields<Content>
代替
Fields<Content>
,以容纳初始化程序中的可选属性。

© www.soinside.com 2019 - 2024. All rights reserved.