Home > Back-end >  Typescript using & operator on string type
Typescript using & operator on string type

Time:07-21

I found this code on TS document. https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html#string-unions-in-types

What does 'string &' mean ? I thought it cound only be used on interfaces.

type PropEventSource<Type> = {
    on(eventName: `${string & keyof Type}Changed`, callback: (newValue: any) => void): void;
};

CodePudding user response:

& is used to make an intersection type. If you're familiar with working with mathematical sets, then you can use that knowledge to understand how it works with types too, since an intersection between two types is very similar to an intersection between two sets.

The type string is the set of all possible strings. So "a", and "aa", and "aaa", etc. keyof Type is the set of all the keys in Type. So as an example, let's assume that Type has 3 keys: "name", "id", and 0 (the last of those being a number, not a string). When you intersect those types together, the result is the intersection of the two sets; string & keyof Type is only the values which show up in both of the sets. So "name" and "id" are found in the intersection, but "aaa" is not (it's only in string) and 0 is not (it's only in keyof Type).

In short: string & keyof Type is the same as keyof Type, but it excludes all numbers.

  • Related