如何在TypeScript中将类型声明为可为空? [英] How to declare a type as nullable in TypeScript?

查看:1601
本文介绍了如何在TypeScript中将类型声明为可为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在TypeScript中有一个界面。

I have an interface in TypeScript.

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

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

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

推荐答案

JavaScript(和TypeScript)中的所有字段都可以具有<$ c $的值c> null 或 undefined

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

您可以使字段可选与nullable不同。

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;
}

与之比较:

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';
}

这篇关于如何在TypeScript中将类型声明为可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆