Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit [key:string]: any from a type in typescript? [duplicate]

Tags:

typescript

Say I have

interface A {
  apple?: number;
  [key: string]: any;
}

interface B extends A {
  banana?: number;
}

I want a type C to extend all from A and all from B except [key: string]: any;. I want a type D to inherit all from B except all from A.

How do I make C and D in typescript?

like image 633
Derek Avatar asked Oct 03 '19 09:10

Derek


People also ask

How do I omit multiple keys in TypeScript?

To omit multiple keys from an object, pass a union of string literals in K . In the next example, we generate a Person type off of SoccerPlayer by removing the team and careerGoals .

What is key string ]: Any in TypeScript?

The {[key: string]: any} syntax is an index signature in TypeScript and is used when we don't know all the names of a type's properties and the shape of their values ahead of time. The index signature specifies that when an object is indexed with a string, it returns a value with any type.

How do you omit a property in TypeScript?

Use the Omit utility type to exclude a property from a type, e.g. type WithoutCountry = Omit<Person, 'country'> . The Omit utility type constructs a new type by removing the specified keys from the existing type. Copied!

How does exclude work in TypeScript?

In TypeScript, the Exclude utility type lets us exclude certain members from an already defined union type. That means we can take an existing type, and remove items from it for specific situations.


2 Answers

Pick all from B, remove A index signature:

type C = Pick<B, KnownKeys<B>>;

Pick all from B, exclude all from A, remove A index signature:

type D = Omit<C, KnownKeys<A>>

Type KnownKeys<T> removes the index signature of T, using only the known property keys (credit goes to Mihail Malostanidis and his answers here and here):

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

How do types C and D look like?

type C = {
    banana?: number | undefined;
    apple?: number | undefined;
}

type D = {
    banana?: number | undefined;
}

const c: C = {
    apple: 1,
    banana: 2,
}

const d: D = {
    banana: 2
}

Playground

like image 63
ford04 Avatar answered Oct 06 '22 22:10

ford04


This should work:

type NoStringIndex<T> = { [K in keyof T as string extends K ? never : K]: T[K] };

interface A {
  apple?: number;
  [key: string]: any;
}

type A2 = NoStringIndex<A>
like image 30
ecklf Avatar answered Oct 06 '22 21:10

ecklf