0

I have this code in JavaScript ES6:

data = [{name:'Peter'}];
const first_name = data.find(o => o.Name === 'name').Value;

I want to migrating to TS, in my tsconfig.json file I set:

"noImplicitAny": true, 

and now I'm getting:

 Parameter 'o' implicitly has an 'any' type 

I tried:

const first_name = data.find(o:object => o.Name === 'name').Value;

but then I got:

Error:  ',' expected. 

It's my first day with TS, so, how can I use "Array.find" with TypeScript? Do I need to add a @type library?

2
  • 1
    @type will not be needed. i paste your code to typescriptlang.org/play , turn on noImplicitAny. And i had no error. Pls check it again Commented Feb 10, 2019 at 20:19
  • 1
    const first_name = data.find(o:object => o.Name === 'name').Value; is wrong syntax, try const first_name = data.find((o:object) => o.Name === 'name').Value; with braces Commented Feb 10, 2019 at 20:19

1 Answer 1

2

Your typing is just wrong

data = [{name:'Peter'}];
const first_name = data.find(o => o.Name === 'name').Value;

assuming you have the interface people such as

interface People {
name: string;
}

The type for data will be Array (or People[]). Here you are finding on the Name property (camelcase) instead of name all lowercase

Moreover, you want to get the Value property but this property does not exists in your People interface which is an error…

This will work:

interface People { 
    name: string;
    firstName: string;
}

const data: People[] = [{name: 'Peter', firstName:'Pan'}];
const firstName = data.find(o => o.name === 'name').firstName;

Note that the good naming practice in TS is to use camelCase, therefore you should use "name" and "value" for the properties name (and not PascalCase), same story for the snake_case of first_name which should be firstName

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.