Tig*_*ine 7 typescript typescript-typings typescript2.0
我正在努力理解将字段定义为string | undefined和string?
我们当前的代码使用这样的类型定义:
class Foo {
public bar: string | undefined;
}
Run Code Online (Sandbox Code Playgroud)
当通过 TSLint 运行此代码时,它会注意到并抱怨它:
考虑使用“?” 在其类型中声明此属性而不是 'undefined' 的语法。
现在的问题是使用的?语法是否完全相同,还是我遗漏了细微的差异?
class Foo {
public bar?: string;
}
Run Code Online (Sandbox Code Playgroud)
所以我们string | undefined现在如何使用类型是在这样的检查中:
if (foo.bar) {..} 这会改变吗?
似乎打字稿文档深入探讨了可选类型,但并未真正探讨它在类上下文中的行为方式。
从 Typescript 4.4 开始,您可以使用该exactOptionalPropertyTypes选项使可选属性与type | undefined.
默认情况下,Typescript 实际上会处理这个......
interface Person {
name: string;
age?: number;
}
Run Code Online (Sandbox Code Playgroud)
……和这个一样……
interface Person {
name: string;
age?: number | undefined;
}
Run Code Online (Sandbox Code Playgroud)
换句话说,除了允许您忽略该属性之外,?实际上还将 undefined添加到类型定义中。以下任何分配都是可以接受的:
const tom: Person = {name: "tom", age: 53};
// This is allowed because of `?`, which adds `undefined` to the type
const john: Person = {name: "john", age: undefined};
// This is allowed because of `?`
const mary: Person = {name: "mary"};
Run Code Online (Sandbox Code Playgroud)
但是当使用 时exactOptionalPropertyTypes,可选类型不允许使用第二个:
const tom: Person = {name: "tom", age: 53};
// This is NOT allowed with just `?`. You have to explicitly add `undefined` to the type
const john: Person = {name: "john", age: undefined};
// This is allowed because of `?`
const mary: Person = {name: "mary"};
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅typescript 4.4 发行说明。
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
Run Code Online (Sandbox Code Playgroud)
关于本案:
if (foo.bar) {..}
Run Code Online (Sandbox Code Playgroud)
两种方法都可以(包括 Intellisense 以任何一种方式工作)。
| 归档时间: |
|
| 查看次数: |
2081 次 |
| 最近记录: |