Skip to content

Latest commit

 

History

History
87 lines (68 loc) · 5.02 KB

TS-Thursday - in or i(teratio)n.md

File metadata and controls

87 lines (68 loc) · 5.02 KB

Let's talk about in.

What would be the difference between:

'thursday' in week
weekday in Week

In JavaScript land, we use it as:

const obj = { id: '123' };
'id' in obj; // true

Where it checks if the prop (supplied as a string or a symbol) is defined on the object, or the objects prototype chain. Note that the property can have the value undefined and the check would still return true.

One thing that might not be obvious is that we can use in on arrays as well:

const myArr = ['one', 'two', 'three'];
0 in myArr // true
3 in myArr // false
'one' in myArr // false

There's more to in in JS than what we covered here but that's enough for now.

Let's look at in from a TypeScript perspective then. Important to remember is that it's still valid in all places shown above, but also in a type declaration. And there it behaves quite different.

We'll touch on subjects such as union, mapped types , keyof and probably more, to be able to talk about this little word. But we'll gloss over a lot of details.

We use in when we build a new type with the help of a Mapped Type

type MappedType = {
	[Prop in Union]: AnyType
}

When in is used in this place, it's an iterator that works on each member of a union. So if we try to break this down:

type Weekdays = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday';

type MappedType = {
	[Weekday in Weekdays]: string;
}
// Produces
// { monday: string; tuesday: string; wednesday: string; ...etc }

Here tsc would iterate over Weekdays, assign each member to Weekday, and produce the final type. Something like:

[Weekday in Weekdays]
[Weekday = 'monday']
[monday]: string
monday: string
[Weekday = 'tuesday']
[tuesday]: string
tuesday: string
...

And a union can be created by typing it explicitly by us, or it can be produced by something like keyof.

type MyItem = {
	id: string;
	name: string;
	active: boolean;
}

const myItem: MyItem = {
	id: '123',
	name: 'thing',
	active: true
}

type NewUnion = keyof MyItem;
type NewUnion2 = keyof typeof myItem;

So the gist of it: in obj checks if a property is defined. in Union iterates over a union.

We'll end with a Playground with a few examples and random type manipulation.