gpt4 book ai didi

typescript - TypeScript 可选类型与类型的区别 |不明确的

转载 作者:行者123 更新时间:2023-12-03 18:45:26 24 4
gpt4 key购买 nike

我正在努力理解将字段定义为 string | undefined 之间的区别和 string?
我们当前的代码使用这样的类型定义:

class Foo {
public bar: string | undefined;
}

当通过 TSLint 运行此代码时,它会注意到并提示它:

Consider using '?' syntax to declare this property instead of 'undefined' in its type.



现在的问题是将使用 ?语法工作完全相同还是我遗漏了细微的差异?
class Foo {
public bar?: string;
}

那么我们如何使用 string | undefined类型现在是这样的检查:
if (foo.bar) {..}这会改变吗?

似乎 typescript 文档深入探讨了可选类型,但并未真正探讨它在类上下文中的行为方式。

最佳答案

bar?: string是可选属性,而 bar: string | undefined是必需的:

interface Foo { 
bar?: string
}

interface Foo2 {
bar: string | undefined
}

const foo: Foo = {} // OK
const foo2: Foo2 = {} // error, bar is required
const foo2: Foo2 = {bar: undefined} // OK
关于本案:
if (foo.bar) {..}
两种方法都可以(包括 Intellisense 以任何一种方式工作)。

关于typescript - TypeScript 可选类型与类型的区别 |不明确的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53371363/

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