The error
In Typescript, when you define a variable with the type of string or number, only the defined type can assign to that variable. It is important to note that these type check errors happen when you have the strict mode turned on by setting
Let's take a look at a simple example. My interface
interface PersonId {
id?: number
name: string
}
export const Person = (props: PersonId) =>{
const ids: number[] = []
ids[0] = props.id // Type 'number | undefined' is not assignable to type 'number'
}
Now I am trying to insert the
I can check the
!!props.id && (ids[0] = props.id)
Doing the same thing, but with better readability.
if(!!props.id){
ids[0] = props.id
}
I can use the
ids[0] = props.id!
The above solutions work on a single variable at a time. What if I have an array of objects that I want to convert into a number or string array?
Now I receive a very long array of
const idList: PersonId[] = [
{id: 100, name: "Smith"},
{id: 101, name: "John"},
{id: 102, name: "Satoshi"},
{id: 103, name: "Ravi"}
]
The array is a type of
interface PersonId {
id?: number
name: string
}
My hardcoded array guarantees to have all the id variables filled. But Typescript only cares about what the interface guarantees, and the interface does not guarantee the
interface PersonId {
id?: number
name: string
}
export const Person = (props: PersonId[]) =>{
const idList: PersonId[] = [
{id: 100, name: "Smith"},
{id: 101, name: "John"},
{id: 102, name: "Satoshi"},
{id: 103, name: "Ravi"}
]
const idArray: number[] = idList.filter((list) => // Undefined error in this line
list.id !== undefined
).map((id) => id.id)
console.log(ids1)
}
In the above code, I filter out the idList array to remove the
I can use the
const idArray: number[] = idList.filter((list) =>
list.id !== undefined
).map((id) => id.id!)
I can use the
const idArray: number[] = idList.filter(
(list: PersonId): list is Required<PersonId> =>
list.id !== undefined
).map((id) => id.id)