修复 typescript 错误 index signature in type 'string' only permits reading-ag捕鱼王app官网

修复 typescript 错误 index signature in type 'string' only permits reading

作者:迹忆客 最近更新:2022/10/31 浏览次数:

当我们尝试写入不可变的值(例如字符串)或只读属性时,会出现“index signature in type 'string' only permits reading”错误。 要解决此错误,需要通过替换必要的字符来创建新字符串或将属性设置为非只读

下面是产生该错误地一个示例

const str = 'hello';
// ⛔️ index signature in type 'string' only permits reading.
str[0] = 'z';

typescript index signature in type string only permits reading

字符串在 javascript(和 typescript)中是不可变的,因此我们无法就地更改字符串的值。

相反,我们必须创建一个只包含我们需要的字符的新字符串。

const str = 'hello';
// ✅ 替换索引处的字符
const index = str.indexof('e');
console.log(index); // 👉️ 1
const replacement = 'x';
const replaced =
  str.substring(0, index)   replacement   str.substring(index   1);
console.log(replaced); // 👉️ hxllo

该示例显示如何替换特定索引处的字符串字符。

这是一个代码片段,展示了如何替换字符串中的特定单词。

const str = 'hello world goodbye world';
const word = 'goodbye';
const index = str.indexof(word);
console.log(index); // 👉️ 12
const replacement = 'hello';
const result =
  str.substring(0, index)   replacement   str.substring(index   word.length);
console.log(result); // 👉️ hello world hello world

此代码片段使用与上一个相同的方法,但不是替换单个字符,而是使用单词的长度来替换它。

如果要从字符串中删除字符或单词,请使用 replace 方法。

const str = 'hello world goodbye world';
const removefirst = str.replace(/world/, '');
console.log(removefirst); // 👉️ "hello goodbye world"
const removeall = str.replace(/world/g, '');
console.log(removeall); // 👉️ "hello goodbye"

第一个示例展示了如何从字符串中删除第一次出现的单词 - 我们基本上用空字符串替换单词。

第二个示例删除字符串中所有出现的单词。

注意 ,上述方法都不会改变原始字符串 - 它们会创建一个新字符串。 字符串在 typescript 中是不可变的。

一个不太常见的错误原因是尝试更改只读属性。

const str = 'hello';
// ✅ 确保没有尝试更改“只读”属性
interface readonlyobj {
  readonly [index: string]: any;
}
// 👇️ const p1: person
const p1: readonlyobj = {
  name: 'tom',
};
// ⛔️ error: index signature in type 'readonlyobj'
//  only permits reading.
p1.name = 'james';

如果我们遇到这种情况,在需要更改其值时将该属性设置为非只读

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

在 typescript 中返回一个 promise

发布时间:2023/03/19 浏览次数:586 分类:typescript

本教程讨论如何在 typescript 中返回正确的 promise。这将提供 typescript 中 returns promise 的完整编码示例,并完整演示每个步骤。

在 typescript 中定义函数回调的类型

发布时间:2023/03/19 浏览次数:1445 分类:typescript

本教程说明了在 typescript 中为函数回调定义类型的ag捕鱼王app官网的解决方案。为了程序员的方便和方便,实施了不同的编码实践指南。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便
网站地图