gpt4 book ai didi

typescript - 如何在 TypeScript 中将类型声明为可为空?

转载 作者:IT老高 更新时间:2023-10-28 13:15:43 24 4
gpt4 key购买 nike

我在 TypeScript 中有一个界面。

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

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

最佳答案

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

您可以使字段可选不同于可为空。

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 - 如何在 TypeScript 中将类型声明为可为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17220114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com