There is an error when I want to destructuring the object:
Property 'name' does not exist on type 'ItemType | undefined'.ts(2339)
App.tsx
import "./styles.css";
type ItemType = {
id: number;
name: string;
};
export default function App() {
const items: Array<ItemType> = [
{ id: 1, name: "Name 1" },
{ id: 2, name: "Name 2" }
];
let { name } = items.find((item: ItemType) => {
return item.id === 1;
});
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Codesandbox:
https://codesandbox.io/s/react-typescript-forked-wpwtdx?file=/src/App.tsx
CodePudding user response:
You cannot destruct something when it's potentially null|undefined
.
You need to make sure it is not null|undefined
then destructing would work.
type ItemType = {
id: number;
name: string;
};
function App() {
const items: Array<ItemType> = [
{ id: 1, name: "Name 1" },
{ id: 2, name: "Name 2" }
];
const item = items.find(item => item.id === 1);
if(item){
const {name} = item;
}
}
CodePudding user response:
You can just get your object using find
function:
let item = items.find(item => item.id === 1);
Then check if item
is null or undefined. If it isn't, you can access its name by item.name
:
let name = item && item.name
Code below
import "./styles.css";
type ItemType = {
id: number;
name: string;
};
export default function App() {
const items: Array<ItemType> = [
{ id: 1, name: "Name 1" },
{ id: 2, name: "Name 2" }
];
let item = items.find(item => item.id === 1);
let name = item && item.name;
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
CodePudding user response:
It is not recommended to destructure object which can be undefined
, however, you can get value using obj?.propertyname
or obj?.array?.[0]?.propertyname
.
And yes using array.find()
for finding element in array is definitely going to be return undefined
as array.find()
returns found object or undefined.
But if you are very sure that you will always find an object from an array then in typescript you should use array.find()!
in this way obviously it's not recommended as best practices you can then overcome your issue by not using destructuring on array.find()