What's new
  • Do not create multi-accounts, you will be blocked! For more information about rules, limits, and more, visit the Help Page Found a dead link? Use the report button!
  • If no files are available, please contact me or reply in the thread. I will update them immediately.

How to create a type which must contain each key of a schema, but may also contain other keys?

To create a TypeScript type that requires all keys of a given schema but allows additional keys, you can use an intersection of the schema type and an object type that permits extra properties. Here's how you can do it:

Example:

JavaScript:
type Schema = {

  requiredKey1: string;

  requiredKey2: number;

};



// Create a type that requires all keys of Schema but allows additional keys

type ExtendedType = Schema & { [key: string]: any };





---

Explanation:

1. Schema: This is the base schema type that specifies the required keys (requiredKey1 and requiredKey2 in this case).


2. [key: string]: any: This represents an index signature that allows additional keys of any type.



With Schema & { [key: string]: any }, the type ensures:

All keys defined in Schema are required.

Additional keys (beyond those in Schema) are allowed.



---

Example Usage:

JavaScript:
const validObject: ExtendedType = {

  requiredKey1: "hello",

  requiredKey2: 42,

  additionalKey: "I am extra",

};



const invalidObject: ExtendedType = {

  requiredKey1: "hello",

  // Missing requiredKey2, so this will throw a TypeScript error

};





---

Stronger Typing for Additional Keys

If you want to restrict the type of additional keys, you can adjust the index signature accordingly. For example:

To allow only string values for additional keys:

JavaScript:
type ExtendedType = Schema & { [key: string]: string };
To allow additional keys with values of specific types:

JavaScript:
type ExtendedType = Schema & { [key: string]: string | number };







---
 
Back
Top