1

I would like to combine two objects in TypeScript and include only the keys that exist in the first object

Below are my code.

type User = {
  username: string
  passcode: number;
}

const userA: User = {
  username: 'A',
  passcode: 1234
}

const updateValues = {
  username: 'B',
  unexpectedKey: "I shouldn't be here. But I exsits in users' post request"
}

// Update userA
for (const key in updateValues) {
  if (key in userA) {
    // We know that `key` has the type `keyof User` now
    userA[key] = updateValues[key]
  }
}

But TypeScript reports the following errors.

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User'.
  No index signature with a parameter of type 'string' was found on type 'User'.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ username: string; unexpectedKey: string; }'.
  No index signature with a parameter of type 'string' was found on type '{ username: string; unexpectedKey: string; }'.

How can I fix these errors with type assertion?

1 Answer 1

3

You need to declare an Index Signature on your type User.

You can read in more detail here: Index Signatures

type User = {
  [username:string] : string | number;
  passcode: number;
}

type UserUpdated = {
  [username:string] : string;
  unexpectedKey: string;
}

const userA: User = {
  username: 'A',
  passcode: 1234
}

const updateValues: UserUpdated = {
  username: 'B',
  unexpectedKey: "I shouldn't be here. But I exsits in users' post request"
}

// Update userA
for (const key in updateValues) {
  if (key in userA) {
    // We know that `key` has the type `keyof User` now
    userA[key] = updateValues[key]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.