#527Medium

Append to object

Implement a Generic Type that can append a new field to any object type. Master mapped types in TypeScript in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement a Generic Type that can append a new field to any object type. For that you take a key and a value and append it to the object type.

Challenge Instructions: Append to object

Medium

Implement a type that adds a new field to the interface. The type takes the three arguments. The output should be an object with the new field.

For example

type Test = { id: '1' }
type Result = AppendToObject<Test, 'value', 4> // expected to be { id: '1', value: 4 }

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
// Video Solution: https://youtube.com/watch?v=CxPfcubGoGA

/* _____________ Your Code Here _____________ */

type AppendToObject<T, U, V> = any

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '../helpers'

type test1 = {
  key: 'cat'
  value: 'green'
}

type testExpect1 = {
  key: 'cat'
  value: 'green'
  home: boolean
}

type test2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
}

type testExpect2 = {
  key: 'dog' | undefined
  value: 'white'
  sun: true
  home: 1
}

type test3 = {
  key: 'cow'
  value: 'yellow'
  sun: false
}

type testExpect3 = {

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Video Walkthrough

Detailed Explanation

type AppendToObject<T, U extends PropertyKey, V> = {
  [Key in keyof T | U]: Key extends keyof T ? T[Key] : V
}

How it works:

This challenge helps you understand TypeScript's advanced type system and how to apply this concept in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts

Stay Updated

Get the latest TypeScript tips, tutorials, and updates delivered straight to your inbox.

No spam, unsubscribe at any time.