Oli*_*xon 5 optional dart union-types
我对 dart 还很陌生,我环顾四周,看不到任何基本选项的选项,例如 TypeScript 中的示例。
请查看评论的属性。'用户名'。
我定义我的模型。
type User {
uid: string,
// Not chosen yet. The team knows this might be null from the '?' Might never be chosen.
username?: string
accountType: 'email'|'facebook' // Also no union types in Dart?
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能在 Dart 中实现标记编译时警告/错误的相同功能?
如果我们有条件解包,例如 user.?username 也会很好。
Swift、Java、TypeScript、Flow、C# 都有这个。它非常方便。
我会写:
class User {
final String uid;
final String username;
final AccountType accountType;
User(this.uid, this.userName, this.accountType) {
ArgumentError.checkNotNull(uid, "uid");
ArgumentError.checkNotNull(accountType, "accountType");
}
}
enum AccountType { email, facebook; }
Run Code Online (Sandbox Code Playgroud)
Dart 还没有不可为 null 的类型,因此您必须手动检查 null 。您无法收到编译时警告。我们希望“很快”引入不可空类型作为默认类型,此时您应该能够编写String? userName;
. 您已经可以使用user?.userName?.toUpperCase()
有条件地调用可能为 的值的方法null
。
Dart 没有联合类型,但这里使用的是枚举类型,Dart 确实有。它们不可能像 Java 的枚举类型那样复杂,但是对于两个值之间的简单选择,它们已经足够了。
归档时间: |
|
查看次数: |
3609 次 |
最近记录: |