➠ TS: Next Level Index Signatures Inside Interfaces and Types
With Typescript we can make our interfaces flexible as to what kind of properties it will accept. Why would this be helpful you may ask, well there are various situations where we need to define the TS compiler to more open to other properties besides the ones defined in the interface. These would include but not limited to:
- The interface will have more properties than is reasonable to define.
- We intend to access the properties dynamically via bracket notation
myObj[value]
.
So lets take a look how this can be done
interface Pet {
// allows any property value of type string
// what if we want more control over possible properties
[key: string]: string
}
const myPet: Pet = {
// all valid values
// what if we have a general rule about our props naming convention?
foo: 'foo',
bar: 'bar',
kbgyb: '??'
}
This approach maybe a bit too flexible and we have a pattern our properties will look
interface Pet {
// by adding the prefix 'content-' we can lock down part of the props name
[key: `content-${string}`]: string
}
const myPet: Pet = {
'content-type': 'foo', // valid property name
two: 'bar' // invalid property name as it is not prefixed with 'content-'
}
Let us take this another step further and define the different values our interface / type can accept.
type StringProps = 'type' | 'name' | 'breed';
type StringPet { [key in StringProps]: string }
// same as this
interface StringPet {
type: string;
name: string;
breed: string;
}
const myPet: Pet = {
type: 'foo', // valid property name
two: 'bar' // invalid property name
}
By making use of StringProps
we can reduce the interface from 5 lines of code to 2 also without having to write string
3 times as well. This approach can be expanded even further:
type StringProps = 'type' | 'name' | 'breed' | 'eyeColor';
type StringPet { [key in StringProps]: string }
type IntProps = 'age' | 'weight' | 'legs';
type IntPet { [key in IntProps]: number }
type BoolProps = 'wings' | 'claws' | 'fur';
type BoolPet { [key in BoolProps]: boolean }
// here we intersect two types together into one
// note: types are intersected, not extended like interfaces are
type WholePet = IntPet & StringPet & BoolPet;
// WholePet in the more verbose view looks like this
interface WholePet {
type: string;
name: string;
breed: string;
eyeColor: string;
age: number;
weight: number;
legs: number;
wings: boolean;
claws: boolean;
fur: boolean;
}
The above approach not only brings control over index signature, but can also be used to make our interfaces and types much more scalable. We are not forced to repeat ourselves with primitive types like string
, number
, or boolean
.
If we want to change the primitive type for one of our properties, we simply move it to appropriate Prop type like from IntProps
to StringProps
.
Thanks for reading!
...Zur Startseite
➤ Ähnliche Beiträge für 'TS: Next Level Index Signatures Inside Interfaces and Types'
Abstract Class vs Interface in C#: Analyzing the Pros and Cons
vom 394.26 Punkte
In object-oriented programming, abstract classes and interfaces serve as blueprints for creating objects in C#. While they have some similarities, they each have unique features that make them suited for different situations.
In this article, we will t
Boost Your JavaScript with JSDoc Typing
vom 393.55 Punkte
There are many reasons why you can't or don't want to use TypeScript in your project. One common reason is that you are using a legacy codebase that is not compatible with TypeScript. Or the switch to TypeScript is harder than everyone tells you. For wh
Difference between types and interfaces in Typescript
vom 361.08 Punkte
It is common for beginners to get confused about types and interfaces in TypeScript, especially if they are new to typed programming languages. It is straightforward to start with TypeScript, but sometimes we need to think more about our best use cas
React and NodeJS Authentication with Refresh & Access Tokens: A Step-by-Step Guide
vom 342.09 Punkte
This article was originally published at https://whatisweb.dev/react-and-nodejs-authentication-with-refresh-access-tokens-a-step-by-step-guide
The most common way of performing authentication in Single Page Applications (SPA) is through the use of JSON Web Tokens (JWT). While JWT-based authentication is easy to implement,
AN Introduction to GraphQL
vom 339.94 Punkte
What is graphql ?
GraphQL is an open-source query language and runtime for APIs (Application Programming Interfaces). It was developed by Facebook and released publicly in 2015. GraphQL provides a flexible and efficient approach to fetching and manip
NestJS Authentication with OAuth2.0: Configuration and Operations
vom 330.23 Punkte
Series Intro
This series will cover the full implementation of OAuth2.0 Authentication in NestJS for the following types of APIs:
Express REST API;
Fastify REST API;
Apollo GraphQL API.
And it is divided in 5 parts:
Configuration and
Crypton - Library Consisting Of Explanation And Implementation Of All The Existing Attacks On Various Encryption Systems, Digital Signatures, Hashing Algorithms
vom 311.78 Punkte
Crypton is an educational library to learn and practice Offensive and Defensive Cryptography. It is basically a collection of explanation and implementation of all the existing vulnerabilities and attacks on various Encryption Systems (Symmetric and Asymmetric), Digital Signatures, Message Authentication Codes and Authenticated
How to learn and use TypeScript + the bits no one teaches you.
vom 305.12 Punkte
Intro
In this article, I will provide you with tools and a mental framework that will help you learn and work with TypeScript, effectively. I will show you that learning TypeScript from a JavaScript background is not as daunting as it may
Building a full-stack TypeScript application with Turborepo
vom 300.84 Punkte
Written by Omar Elhawary✏️
Whether you're building a full-stack application or an application composed of multiple frontend and backend projects, you'll probably need to share parts across projects to varying extents.
It could be types, utilities,
How to Learn and Use TypeScript: A Comprehensive Beginner's Guide
vom 297.06 Punkte
In this article, I will provide tools and a mental framework to help you effectively learn and work with TypeScript. I will show you that learning TypeScript from a JavaScript background is more manageable than it may seem. To achieve this, we will be
Create a Modern Application with Django and Vue
vom 287.2 Punkte
Download source code here. ⬅️
Previously, in the beginner's roadmap to web development tutorial series, we talked about how to create a web application using Django, a full-stack Python-based web framework that follows the MTV design pattern. We call it full-stack because we ca
50 chart types for data visualization explained
vom 281.2 Punkte
Charts are a powerful tool for data visualization, but with so many chart types available, it can be overwhelming to choose the right one. To help, we've compiled a list of the top 50 chart types. From basic to complex, this list covers a wide range of