热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在TypeScript中定义可选为空的类型?-DeclaringTypesasOptionallyNullableinTypeScript

在TypeScript中,我定义了一个名为`Employee`的接口,其中包含`id`和`name`属性。为了使这些属性可选为空,可以通过使用`|null`或`|undefined`来扩展其类型定义。例如,`id:number|null`表示`id`可以是数字或空值。这种类型的灵活性在处理不确定的数据时非常有用,可以提高代码的健壮性和可维护性。

I have an interface in TypeScript.

我在TypeScript中有一个接口。

interface Employee{
   id: number;
   name: string;
   salary: number;
}

I would like to make 'salary' as a nullable field (Like we can do in C#). Is this possible to do in TypeScript?

我想把'薪水'作为一个可以为空的领域(就像我们在C#中所做的那样)。这可以在TypeScript中做到吗?

4 个解决方案

#1


155  

All fields in Javascript (and in TypeScript) can have the value null or undefined.

Javascript(和TypeScript)中的所有字段都可以具有null或undefined值。

You can make the field optional which is different from nullable.

您可以将字段设为可选字段,该字段与可空字段不同。

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

与之比较:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

#2


39  

Union type is in my mind best option in this case:

在这种情况下,联盟类型是我心目中的最佳选择:

interface Employee{
   id: number;
   name: string;
   salary: number | null;
}

// Both cases are valid
let employe1: Employee = { id: 1, name: 'John', salary: 100 };
let employe2: Employee = { id: 1, name: 'John', salary: null };

#3


28  

Just add a question mark ? to the optional field.

只需添加问号?到可选字段。

interface Employee{
   id: number;
   name: string;
   salary?: number;
}

#4


4  

i had this same question a while back.. all types in ts are nullable, because void is a subtype of all types (unlike, for example, scala).

我有一段时间也有同样的问题.. ts中的所有类型都可以为空,因为void是所有类型的子类型(例如,scala不同)。

see if this flowchart helps - https://github.com/bcherny/language-types-comparison#typescript

看看这个流程图是否有帮助 - https://github.com/bcherny/language-types-comparison#typescript


推荐阅读
author-avatar
小寒风
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有