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?
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 .
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.
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!
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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With