修复 TypeScript 错误 index signature in type ‘string’ only permits reading

当我们尝试写入不可变的值(例如字符串)或只读属性时,会出现“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';

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