Type narrowing example with twoslash extension

Example from the docs

https://twoslash.studiocms.dev/usage/banners/callouts/

type-narrowing.ts
const
const hi: "Hello"
hi
= "Hello"
const msg = `${
const hi: "Hello"
hi
}, world`
const msg: "Hello, world"

Example of type narrowing

Use the in statement:

astro-component.ts
type
type Contents = ({
header: string;
body: string;
} | {
imageURL: string;
})[]
Contents
=
interface Array<T>
Array
<{
header: string
header
: string;
body: string
body
: string } | {
imageURL: string
imageURL
: string }>
const
const contents: Contents
contents
:
type Contents = ({
header: string;
body: string;
} | {
imageURL: string;
})[]
Contents
= [{
imageURL: string
imageURL
: "/images/services/3.png",
}, {
header: string
header
: "This is a header",
body: string
body
: `Some text goes here..`,
}]
const contents: Contents
contents
.
Array<{ header: string; body: string; } | { imageURL: string; }>.map<void>(callbackfn: (value: {
header: string;
body: string;
} | {
imageURL: string;
}, index: number, array: ({
header: string;
body: string;
} | {
imageURL: string;
})[]) => void, thisArg?: any): void[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
((
item: {
header: string;
body: string;
} | {
imageURL: string;
}
item
) => {
Message: using `in` keyword allows for type differentiation
if ("imageURL" in
item: {
header: string;
body: string;
} | {
imageURL: string;
}
item
) {
item
item: {
imageURL: string;
}
} else {
item
item: {
header: string;
body: string;
}
}
})

References

Oida Dev, Feb 3/2020