0
export type MyType = {
  age: number;
  test: boolean,
  str: string,
  preview: [{ [key: string]: string | number }];
};

let data: MyType = JSON.parse(JSON.stringify({
  age: 2,
  str: "string",
  test: false,
  preview: [{ 'moon ': 'light' }]
}));

let objKeys = Object.keys(data) as Array<keyof MyType>
objKeys.forEach((item: keyof MyType) => {
  data[item] = data[item]
})

error : https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBDAnmYcCyiAqzUF44DeAsAFBxwCGA5sAFxwB2ArgLYBGwUA3KeTMAGcY9NhAgAbYBQYAaXnCFR6igJYMqcsnDBRgANxXAA7vQDaBOKYDWwRMphQ1VALr3H6uAB9GrDlDgAvs48JAEhpJLwACYUMBT0GNgocPgAUgDKAPIAcgB0YBRQAsAAFBk5uarqKgBmiCXEWtR0cABMmuSK9ABEVVTdHQiCwnA1FOLFgzr6hiaWFgDkLGIMcAv0C+IqVAAWMAuBzqQBAJQn4SSRcBBsAFYA0rYCKXCZd8AAxjC5NogCJTE4idKM8AIJQKAURAAHl+EBq6CwOAAfKQbg8nrkatAAKIUD47EolFT8Fj0OEIxI4YG4ZGEeSAiimEnAFjOF6M5mko6hE5AA

How can I fix the type error, I just try assign value to each prop

VincentGuo
  • 247
  • 2
  • 9
  • `x` is type `string`. `ts` doesn't have a string index signature, as the error says, so `a[x]` implicitly has the type `any` (since TypeScript has no idea what it is). See the linked question or [most of these](/search?q=%5Btypescript%5D+expression+of+type+%27string%27+can%27t+be+used+to+index+type). Please [search](/help/searching) before posting. – T.J. Crowder Apr 26 '22 at 16:13
  • (Side note: `JSON.parse(JSON.stringify(someObject))` isn't a good way to make a copy of an object. It makes a pointless round-trip through text, is lossy, and fails for anything with circular references. For shallow copies, use spread. For deep copies, [see here](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript).) – T.J. Crowder Apr 26 '22 at 16:14
  • pls see demo here: is not assignable to type 'never' https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBDAnmYcCyiAqzUF44DeAsAFBwCGA5sAFxwB2ArgLYBGwUA3KQsAM4warCBAA2wcvQA0PAVBpyAlvUoySYKMABui4AHc6AbQJxDAa2CI6SlQF1rMKMspwAPgxbsocAL63uJD4BpOLwACbkMORwdBjYKHC4AFIAygDyAHIAdGDkUHzAABSpmVk2lIoAZoiFhDxwFNR0AExqDXByNABE5V1tDTD8gpXkogX9Gtq6BqYmAOTMIvRwc3RzooqUABYwc762pD4AlEfBZO0NoXAQrABWANKWfIlwaXfAAMYwWRaIfIURKJHCjPACCUCg5EQAB5fhBKugsDgAHz1D4QegCOAgHEgF4Xa53R5-LKVaAAUXIHy2hUKikGzDocIRcRwwNwyLq5wJDUB5EM9OAzFsuD5AoZB25PN8RyAA – VincentGuo Apr 26 '22 at 16:39

0 Answers0