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

标签 typescript

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/

相关文章:

angular - 如何在 Angular/TypeScript 中组合两个 URLSearchParams?

angular - 点击事件无效, "co.console.log() is not a function"

Typescript 导入语句

angular - 从一个组件访问变量到另一个组件

javascript - 什么决定了 'bot.dialog' 何时传递到 Microsoft Bot Framework 中 waterfall 的下一个函数? ( Node .js)

javascript - WooCommerce API 中的 401 发布方法未经授权

typescript - 在 onPress 中 React Native Typescript Formik 的 handleSubmit 类型

javascript - 优化大型 TypeScript 文件的编译

typescript - 使用 tslint 时如何忽略 *.d.ts 文件?

javascript - 双向绑定(bind) : array of numbers within angular application