gpt4 book ai didi

TypeScript:类型 'string | undefined' 不可分配给类型 'string'

转载 作者:行者123 更新时间:2023-12-03 20:55:19 29 4
gpt4 key购买 nike

interface SomeType {
a: string;
b?: string;
}

const foo: SomeType = {
a: 'hello',
b: 'there'
};

const bar: SomeType = {
a: 'hello'
};
bar.b = 'there';

// Error on this line
const str: string = foo.b;

// These lines have no error
const str2: string = foo.b ? foo.b : '';
const str3: string = foo.b!;
const str4: string = bar.b;

在上面的例子中,我们有 2 种口味创建了一个 SomeType 的对象。 ,它有一个可选属性 b .申报时 foo ,我们正在设置 b 的值创建对象时。对于 bar ,我们设置的值为 b创建对象后。

创建第一个字符串时, str ,有一个错误:

Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'.ts(2322)



使用 str2 的方法可以缓解此错误和 str3 .我知道在这些例子中,我们要么检查 foo.b 的值。或断言我们知道 foo.b有一个值(value)。

我不明白为什么 str4 时不出现错误被 build 。为什么 TypeScript 能够检测到 bar.b不是 undefined但它无法检测到 foo.b 的相同内容?我们设置导致此错误的属性的方式是什么?

( typescript 版本 3.8.2)

最佳答案

删除 SomeType来自行 const foo: SomeType = ...将使代码工作。

interface SomeType {
a: string;
b?: string;
}

const foo = {
a: 'hello',
b: 'there'
};

const bar: SomeType = {
a: 'hello'
};
bar.b = 'there';

// No more error on this line
const str: string = foo.b;

// These lines have no error
const str2: string = foo.b ? foo.b : '';
const str3: string = foo.b!;
const str4: string = bar.b;

在原始代码中,您正在转换对象 { a:..., b:...}interface .在这种情况下 SomeType :

const foo: SomeType = {
a: 'hello',
b: 'there'
};

最简单的例子是,如果你修改 str4 的最后一行添加类型转换,你会产生同样的错误:

const str4: string = (bar as SomeType).b; // error, because of the cast

关于TypeScript:类型 'string | undefined' 不可分配给类型 'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61130603/

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