更漂亮的 TypeScript 匿名类声明?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16179542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:48:55  来源:igfitidea点击:

A more beautiful TypeScript anonymous class declaration?

typescript

提问by Christopher King

Is there a more beautiful way to express an anonymous class(?) with typed members in typeScript than this?

在 typeScript 中,有没有比这更漂亮的方式来表达带有类型成员的匿名类(?)?

class Foo {
    member = {
        aNumber = <number>undefined;
        aBoolean = <bool>undefined;
    }
}

回答by Ryan Cavanaugh

The only anonymousalternative would be:

唯一的匿名替代方案是:

class Foo {
    member: { aNumber?: number; aBoolean?: bool; } = {
        aNumber: undefined,
        aBoolean: undefined
    }
}

You're usually better off just writing an interfaceso you can name the type.

你通常最好只写一个,interface这样你就可以命名类型。

回答by basarat

Since members are undefined by default you could simply go with:

由于默认情况下成员未定义,您可以简单地使用:

class Foo {
    member:{aNumber:number;aBoolean:bool;} = <any>{};
}

回答by Micheal Hill

In newer versions of typescript, this can be achieved using optional properties:

在较新版本的打字稿中,这可以使用可选属性来实现:

class Foo {
    member: { aNumber?: number; aBoolean?: boolean; } = {}
}