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

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

问题描述

我在 TypeScript 中有一个接口.

interface Employee{身份证号码;名称:字符串;工资:数字;}

我想将 salary 设为可空字段(就像我们在 C# 中所做的那样).这可以在 TypeScript 中实现吗?

解决方案

JavaScript(和 TypeScript)中的所有字段都可以具有 nullundefined 值.

您可以将字段设为可选,这与可为空不同.

interface Employee1 {名称:字符串;工资:数字;}var a: Employee1 = { name: 'Bob', 薪水: 40000 };//好的var b: Employee1 = { name: 'Bob' };//不行,你必须有薪水"var c: Employee1 = { name: 'Bob', 薪水:未定义 };//好的var d: Employee1 = { 姓名: null, 工资: 未定义 };//好的//好的类 SomeEmployeeA 实现了 Employee1 {公共名称 = '鲍勃';公共工资=40000;}//不正常:必须有薪水"类 SomeEmployeeB 实现了 Employee1 {公共名称:字符串;}

比较:

interface Employee2 {名称:字符串;薪水?:数字;}var a: Employee2 = { name: 'Bob', 薪水: 40000 };//好的var b: Employee2 = { name: 'Bob' };//好的var c: Employee2 = { name: 'Bob', 工资: 未定义 };//好的var d: Employee2 = { 姓名: null, 工资: 'bob' };//不行,薪水必须是数字//好的,但没有太大意义类 SomeEmployeeA 实现了 Employee2 {公共名称 = '鲍勃';}

I have an interface in 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?

解决方案

All fields in JavaScript (and in TypeScript) can have the value null or 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';
}

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

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