0

this question solution is already available in stackoverflow but, i am still confuse,i have use same as they answer still go this error please help me to get out of this error thank you my list of object is

 const typeValue = [
        {name: "Subscription", value: "subscription", rank: 2},
        {name: "Single", value: "single", rank: 3},
        {name: "Trial", value: "trial", rank: 0},
        {name: "Unlimited", value: "unlimited", rank: 1000},
        {name: "Promo", value: "promo", rank: 1},
        {name: "Test", value: "test", rank: 0},
        {name: "Brand", value: "brand", rank: 3}
    ]

any i want to find rank number

  rank: typeValue.find(x => x.value === snapshot.data().type).rank    
1
  • Can you provide the error you are getting? Commented Dec 31, 2021 at 4:01

3 Answers 3

0
typeValue.find(x => x.value === snapshot.data().type)

You're trying to find an element in typeValue that satisfies x.value === snapshot.data().type, but snapshot.data().type could be anything so TypeScript is warning that typeValue.find(x => x.value === snapshot.data().type) may return undefined.

If you want to tell TypeScript that x.value === snapshot.data().type will definitely match one of the elements, you can use !:

rank: typeValue.find(x => x.value === snapshot.data().type)!.rank

You can also use ? if rank can be undefined:

rank: typeValue.find(x => x.value === snapshot.data().type)?.rank
Sign up to request clarification or add additional context in comments.

Comments

0

find will return undefined if it can't find a match, and then it is illegal to call .rank. To solve, use ?.rank instead:

rank: typeValue.find(x => x.value === snapshot.data().type)?.rank

If the problem persists, then you may have to do the same for .type:

rank: typeValue.find(x => x.value === snapshot.data()?.type)?.rank

Comments

0

Declare types for you typeValue array variable :-

const typeValue: { name: string; value: string; rank: number }[] = [
  { name: "Subscription", value: "subscription", rank: 2 },
  { name: "Single", value: "single", rank: 3 },
  { name: "Trial", value: "trial", rank: 0 },
  { name: "Unlimited", value: "unlimited", rank: 1000 },
  { name: "Promo", value: "promo", rank: 1 },
  { name: "Test", value: "test", rank: 0 },
  { name: "Brand", value: "brand", rank: 3 },
];

Also add types for snapshot.data().type, if you didn't declared it already!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.