Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: object with any keys except one

Tags:

typescript

I just want a type like this one:

type ObjectWithAnyKey = { [key: string]: string };

with all keys allowed except a foo key.

How to do that?

like image 839
B. Branchard Avatar asked Oct 28 '19 15:10

B. Branchard


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 .

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!

What is omit in TypeScript?

TypeScript provides a number of utility types which are used to solve a particular problem that using types in Javascript creates. One very useful utility type used in TypeScript is the Omit type, which lets us customize an already existing type.

What does Keyof do in TypeScript?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.


2 Answers

I think in this case you can use the following definition:

type ObjectWithAnyKeyExceptFoo = {
  [key: string]: string
} & { foo?: never };

The type {foo?: never} has an optional property named foo, whose type is never (which actually is the same as undefined for optional properties). So if you have a property named foo, it can't have a defined value. And actually since undefined & string is never, you can't have a foo property at all. Let's make sure it works:

function acceptAnyKeyAcceptFoo(obj: ObjectWithAnyKeyExceptFoo) { }

acceptAnyKeyAcceptFoo({}); // okay
acceptAnyKeyAcceptFoo({ a: "123" }); // okay
acceptAnyKeyAcceptFoo({ a: "123", foo: "oops" }); // error!
//  ----------------------------> ~~~
// Type 'string' is not assignable to type 'undefined'.
acceptAnyKeyAcceptFoo({ a: "123", foo: undefined }); // error!
//  ----------------> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type 'undefined' is not assignable to type 'string'.

Looks good.


More technical stuff below:

Note that using the intersection (&) here is a little strange, and maybe even cheating a little bit. With an index signature, manually specified properties like foo are required to have values that are assignable to their index signature property type also. The following doesn't work because it violates that:

type BadDefn = {
  [key: string]: string;
  foo?: never; // error!
//~~~ <-- undefined is not assignable to string
}

Since foo may be undefined, but string is not, the compiler is unhappy. Never mind that most values from the index signature actually will be undefined and not string (e.g., const obj: ObjectWithAnyKeyExceptFoo = {a: "123"} has an a property of type string, but what if you access its b property? You will get undefined at runtime, but the compiler says string). But that's the way index signatures are, I guess.

The intersection definition is essentially the same thing as the disallowed type above, except that it sidesteps the compiler error. There are often issues with doing this intentionally to violate the index signature (see this question), but we don't actually want to use that violating property. We don't want foo properties at all, and since the compiler sees the foo property as string & undefined, which is never, it's actually better for this use case.

Non-violating single types like these can be made:

type OkayDefnButPossiblyUndefined = {
  [key: string]: string | undefined;
  foo?: never;
}

This one is actually reasonable if you want to represent that obj.b is undefined and not string, but might not be the best fit if you like the current index signature behavior. There's also this one:

type AlsoOkayButRequiresFoo = {
  [key: string]: string;
  foo: never;
}

which is worse, since foo becomes a required property and it's hard to actually initialize something of this type.

End technical stuff


Okay, hope that helps. Good luck!

Link to code

like image 177
jcalz Avatar answered Sep 28 '22 06:09

jcalz


The answer by jcalz is fantastic, definitely worth a detailed read. In my case I want to do this pattern in many places and I enjoy advanced types, hence I wrote this advanced type that implements jcalz's answer via a type that you can export and use freely wherever.

type keyOmit<T, U extends keyof any> = T & { [P in U]?: never }

As with above the same behaviour is observed:

type ObjectWithAnyKeyExceptFoo = keyOmit<{ [key: string]: string }, "foo">

function acceptAnyKeyAcceptFoo(obj: ObjectWithAnyKeyExceptFoo) {}

acceptAnyKeyAcceptFoo({}) // okay
acceptAnyKeyAcceptFoo({ a: "123" }) // okay
acceptAnyKeyAcceptFoo({ a: "123", foo: "oops" }) // error!
//  ----------------------------> ~~~
// Type 'string' is not assignable to type 'undefined'.
acceptAnyKeyAcceptFoo({ a: "123", foo: undefined }) // error!
//  ----------------> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type 'undefined' is not assignable to type 'string'

Also note that you can use this specific type the same as the built in 'Omit' type so you can omit many keys with this (my particular use case)

type ObjectWithAnyKeyExceptFooOrBar = keyOmit<{ [key: string]: string }, "foo" | "bar">

function acceptAnyKeyAcceptFooOrBar(obj: ObjectWithAnyKeyExceptFooOrBar) {}

acceptAnyKeyAcceptFooOrBar({}) // okay
acceptAnyKeyAcceptFooOrBar({ a: "123" }) // okay
acceptAnyKeyAcceptFooOrBar({ a: "123", foo: "oops" }) // error!
//  ---------------------------------> ~~~
// Type 'string' is not assignable to type 'undefined'.
acceptAnyKeyAcceptFooOrBar({ a: "123", bar: "oops" }) // error!
//  ---------------------------------> ~~~
// Type 'string' is not assignable to type 'undefined'.
acceptAnyKeyAcceptFooOrBar({ a: "123", foo: "oops", bar: "2nd oops" }) // error!
//  ---------------------------------> ~~~          ~~~
like image 20
Jamie Shepherd Avatar answered Sep 28 '22 06:09

Jamie Shepherd