What is the significance of the KnownKeys type within IndexedDB?

type FilteredKeys<T> = {
  [K in keyof T]: string extends K ? never : number extends K ? never : K;
} extends { [_ in keyof T]: infer U }
  ? U
  : never;

This type is quite puzzling to me. I find it difficult to grasp its purpose. It appears to filter out all string literal properties and create a union type of the remaining keys.

declare let b: FilteredKeys<{ sample: 56, 99: 'example' }>
b = 'example' // Works.
// b = 99 Error.
// b = '99' Error.

How does it manage to accomplish this?

Answer №1

It seems that the purpose of KnownKeys is to extract all explicit or "known" keys from a hybrid type containing both hard-coded properties and an index signature (check out this post for more details and credit).

KnownKeys does not affect types without an index signature:

type T11 = KnownKeys<{ test: 34, 23: 'test'}> // "test" | 23
type T12 = keyof { test: 34, 23: 'test'} // same as above

However, when dealing with a hybrid type, there is a distinction:

type T21 = KnownKeys<{ [K: string]: number, foo: number }> // allows extraction of "foo" 
type T22 = keyof { [K: string]: number, foo: number } // string | number, which may not be very useful...

This functionality works because a mapped type returns both the index signature and explicit properties:

type T3 = {[K in keyof { [K: string]: number, foo: number }]: number}
// { [x: string]: number; foo: number; } includes the signature and the "foo" property

We can assign a value of never to the signature part [x: string]: number using the type expression

string extends K ? never : number extends K ? never : K
. Then filter out all properties with a never value by
extends { [_ in keyof T]: infer U } ? U : never;
. Code

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The correlation between subject matter and the workflow of resilience

I am seeking clarity on how Subjects behave when used with the resiliency operators, specifically retry and retryWhen. The code samples below may differ slightly from the JSBin examples as I have used arrow functions and types for better understanding. Th ...

Describing this as a function parameter/return type in Typescript

I am looking to create a function that can reference the current object's type in its parameter and return types, like so: inside .d.ts: interface Object { add(object: Partial<this>): this; } within .js: Object.prototype.add = function(obj ...

Performing optimized searches in Redis

In the process of creating a wallet app, I have incorporated redis for storing the current wallet balance of each user. Recently, I was tasked with finding a method to retrieve the total sum of all users' balances within the application. Since this in ...

Obtain the reference to the child element of the nativeElement

As a newcomer to Angular, I am currently working with Angular 7. Within our project, we have implemented a button component labeled as "Send Email." When this button is clicked on the webpage where it is displayed, it triggers the default email sending win ...

Having difficulty accessing an element within ng-template during the unit test writing process with Jasmine

I am encountering an issue when trying to access a button inside an ng-container in my testing environment. Despite manually setting the value of the ngIf condition to true, the elements inside are not being rendered. Here is what I have attempted so far: ...

Issues with Vite's global import feature not functioning properly in a production build

My current setup involves loading all markdown files within a directory using a glob import. The code snippet below depicts this functionality: const useGetChangelogs = () => { const [changelogs, setChangelogs] = useState<string[]>([]); useEf ...

Navigating between pages has become challenging due to issues with the navbar, sidebar,

I successfully developed 4 Angular components: 1st component: menu 2nd component: header 3rd component: home 4th component: login The menu component features a sidebar/navbar created using Material UI. The login component consists of the login page. Howe ...

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

Is it possible to assign an object literal to a typed variable in TypeScript? Can you also specify the typeof object literal?

Consider a scenario where you have the following type definition: type MyType = { A: number | string } If you try to assign a value like this, TypeScript will correctly flag it as an error: const myValue1: MyType = { A: 123, B: "Oh!", // This wil ...

The role of callback functions in TypeScript

As I embark on my journey with Angular 2 and TypeScript, one concept that has me a bit puzzled is how to implement callback functions. I understand that this might be a basic question, but when I look at this typical JavaScript code: someOnject.doSomethin ...

The correct method for recording a personalized directive with added functionality using the then function

Here's a full Typescript Cypress project. Encountering an error while trying to use the custom command below: Usage: cy.restGetUserId(userEmail).then(userId => { //do something with userId }); Custom command: Cypress.Commands.add ...

Using AWS StepFunctions to add a prefix to an input string

How can I use TypeScript and CDK to create a task that prefixes one specific field in the input while leaving the rest unchanged? Input: { "field1": "foo", "field2": "bar" } Desired output: { "field1" ...

Error message shows explicit Typescript type instead of using generic type name

I am looking to use a more explicit name such as userId instead of the type number in my error message for error types. export const primaryKey: PrimaryKey = `CONSUMPTION#123a4`; // The error 'Type ""CONSUMPTION#123a4"" is not assignable to ...

Seeking assistance with managing Yarn workspaces

My current project involves working on a React Native application for a client. After I had already written a significant amount of code, my client requested a new feature to be added. This feature should have been simple to implement, but due to the compl ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Top method for transferring information from a service to a dynamic format in Angular5

Looking for the most efficient method to populate a form with data from a service in Angular 5. My goal is to keep component code to a minimum and have the variable-data stored within services rather than components. The content is loaded through a second ...

Angular 5 - Issue with Conditional Validator Functionality Being Ineffective

If the email field is not left empty, then the re-email field must be marked as 'required'. In order to achieve this functionality, I have implemented conditional validators for the re-email field using the code snippet below: HTML <div cla ...

Guide on tracking the cursor using Angular

Recently, I developed a basic application in Angular that incorporates animations. You can check out the StackBlitz here to see it in action. The app features states that we can switch to control where an eye is looking. Currently, I am looking for a way ...

Convert an array with three dimensions into a two-dimensional array that includes tuples with two immutable string values

Consider the array below with multiple dimensions: type ParsedLine = [string, string]; type ParsedLines = [ParsedLine, ParsedLine] const myArray: (ParsedLine | ParsedLines)[] = [ ['something', 'somethingElse'], [['foo', & ...

Angular has a built-in function to determine the next ID after deletion of some items

I am currently facing a situation where I have a list of contacts in a detailed view and navigating through them using the following code: <nav> <a [routerLink]="['/details', friend.id - 1 ]" *ngIf="!(friend.id == 1)"> P ...