Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ TypeScript Type Negation: How to Forbid Certain Properties

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š TypeScript Type Negation: How to Forbid Certain Properties


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

Type negation in TypeScript allows you to create types that explicitly exclude certain properties. Usually, we define types that specify what properties an object must have to satisfy that type. With type negation, we want to do the opposite: We specify which properties an object must not have. You can think of this as reserved properties.

Let's consider the following example. We have a generic createItem function that inserts a new item into our NoSQL database (e.g. MongoDB, DynamoDB, etc.). The NoSQL database and its tables do not have a defined column schema, that means the item with all its properties is stored as is. However, in order to retrieve the items, we need to define at least one property as a primary key (e.g. in DynamoDB this is the hash key). This is usually an ID as an integer or UUID, which can be defined either by the database or the application.

function createItem<TItem extends object>(item: TItem): TItem {
  // Database sets ID
  const newItem = db.insert(item);

  return newItem;
}

// Returns object with id { id: "0d92b425efc9", name: "John", ... }
const user = createItem({ name: "John", email: "[email protected]" });

We can call this function with any JavaScript object and store it in our NoSQL database. But what happens if the object we pass in contains an id property?

// What will happen?
//> Will it create a new item?
//> Will it overwrite the item if it exists?
const user = createItem({ id: "0d92b425efc9", name: "John", email: "[email protected]" });

What actually happens depends on the database, of course. A new item could be created, or an existing item could be overwritten, or even an error could be thrown if we are not supposed to specify an external ID. Of course, we can simply add a check to the id property and raise an error ourselves to prevent such cases.

function createItem<TItem extends object>(item: TItem): TItem {
  if('id' in item) throw new Error("Item must not contain an ID");
  // Database sets ID
  const newItem = db.insert(item);

  return newItem;
}

// Throws an error
const user = createItem({ id: "0d92b425efc9", name: "John", email: "[email protected]" });

Let's go one step further and use TypeScript generics and types to prevent such cases from happening in the first place. We simply forbid the item to contain an id property.

type ReservedKeys = {
  id: string;
}

function createItem<TItem extends object>(
  item: TItem extends ReservedKeys ? never : TItem
): TItem {
  if('id' in item) throw new Error("Item must not contain an ID");
  // Database sets ID
  const newItem = db.insert(item);

  return newItem;
}

In this example we define a ReservedKeys type with forbidden keys. These are the properties that should not be allowed for the item. In the function signature, we then use TItem extends ReservedKeys to check if the generic TItem is a subset of ReservedKeys. If it is, we set the element type to the special value never.

Let's go back to our previous example. Now what happens when we specify an object with ID?

// What will happen?
//> TypeScript error: Argument of type '{ id: string; name: string; email: string; }' is not assignable to parameter of type 'never'
const user = createItem({ id: "0d92b425efc9" name: "John", email: "[email protected]" });

TypeScript reports an error that the object we passed to the function doesn't match the expected type.

TypeScript Playground

TypeScript Playground

Of course, we should never rely on static type checking alone to avoid such errors. Checking the property id at runtime within the implementation should always be present. The type negation is rather syntactic sugar to catch possible errors already at compile time and to have a function signature that matches the implementation.

I hope you found this post helpful. If you have any questions or comments, feel free to leave them below. If you'd like to connect with me, you can find me on LinkedIn or GitHub. Thanks for reading!

...



๐Ÿ“Œ TypeScript Type Negation: How to Forbid Certain Properties


๐Ÿ“ˆ 120.23 Punkte

๐Ÿ“Œ Creating Your Own DeepPartial Type in Typescript to Allow Any Subset of Object Properties Deeply


๐Ÿ“ˆ 37.2 Punkte

๐Ÿ“Œ The Big Bang Theory - Staffel 12: Recap zu Folge 9 &quot;The Citation Negation&quot;


๐Ÿ“ˆ 35.37 Punkte

๐Ÿ“Œ I made "TypeScript Swagger Editor", new type of Swagger UI writing TypeScript code in the browser


๐Ÿ“ˆ 32.79 Punkte

๐Ÿ“Œ Mastering CSS Custom Properties: The Senior Developer's Approach to CSS Custom Properties.


๐Ÿ“ˆ 32.66 Punkte

๐Ÿ“Œ How to forbid connections from a set of IPs (CentOS)?


๐Ÿ“ˆ 31.88 Punkte

๐Ÿ“Œ Is there no way to forbid proprietary software from being installed when using Flatpak/Snap?


๐Ÿ“ˆ 31.88 Punkte

๐Ÿ“Œ [LOOOONG] Let's be realistic, if Kismet forbid, Firefox would actually die and cease development.


๐Ÿ“ˆ 31.88 Punkte

๐Ÿ“Œ Typescript: best type checking for the best type safety


๐Ÿ“ˆ 29.82 Punkte

๐Ÿ“Œ Type Narrowing vs Type Casting in TypeScript


๐Ÿ“ˆ 29.82 Punkte

๐Ÿ“Œ Typescript type grouping a union type of objects by any property discriminating these objects.


๐Ÿ“ˆ 29.82 Punkte

๐Ÿ“Œ Typescript Generate Full Path Type And Get Value Type Of Nested Object


๐Ÿ“ˆ 29.82 Punkte

๐Ÿ“Œ Programmiersprache: TypeScript 4.3 flexibilisiert den Zugriff auf Properties


๐Ÿ“ˆ 28.25 Punkte

๐Ÿ“Œ Optional vs. Undefined: Understanding TypeScript's Approach to Required Properties


๐Ÿ“ˆ 28.25 Punkte

๐Ÿ“Œ Extending the Properties of an HTML Element in TypeScript


๐Ÿ“ˆ 28.25 Punkte

๐Ÿ“Œ CVE-2022-45122 | Movable Type 7/Type Premium/Type Premium Advanced cross site scripting


๐Ÿ“ˆ 26.86 Punkte

๐Ÿ“Œ CVE-2022-45113 | Movable Type 7/Type Premium/Type Premium Advanced URL input validation


๐Ÿ“ˆ 26.86 Punkte

๐Ÿ“Œ CVE-2022-43660 | Movable Type 7/Type Premium/Type Premium Advanced os command injection


๐Ÿ“ˆ 26.86 Punkte

๐Ÿ“Œ Python Type Hinting: From Type Aliases To Type Variables and New Types


๐Ÿ“ˆ 26.86 Punkte

๐Ÿ“Œ Top-Level Drop-In to Apply Settings to All Units of a Certain Type


๐Ÿ“ˆ 24.74 Punkte

๐Ÿ“Œ 10 typescript developers you must follow to become typescript expert in 2024


๐Ÿ“ˆ 23.83 Punkte

๐Ÿ“Œ How Types Work in TypeScript โ€“ Explained with JavaScript + TypeScript Code


๐Ÿ“ˆ 23.83 Punkte

๐Ÿ“Œ Introduction to TypeScript โ€” What is TypeScript?


๐Ÿ“ˆ 23.83 Punkte

๐Ÿ“Œ Getting Started with TypeScript: A Quick Introduction From JavaScript to TypeScript!


๐Ÿ“ˆ 23.83 Punkte

๐Ÿ“Œ Getting To Know TypeScript's Partial Type


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ Dynamic return type based on input parameter in TypeScript like Prisma


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ Basic Type Transformations with Typescript


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ Phero: Build type-safe, full-stack apps with TypeScript


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ Use which: Interface or Type Alias in Typescript?


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ How to produce type-safe GraphQL queries using TypeScript ๐Ÿ’ฅ


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ Using the TypeScript generic type to create reusable components


๐Ÿ“ˆ 20.87 Punkte

๐Ÿ“Œ What are Type Predicates in Typescript?


๐Ÿ“ˆ 20.87 Punkte











matomo