score:92
items: object[],
While technically it is a JavaScript object, the type can be better. For Typescript to correctly help you identify mistakes when accessing objects properties, you need to tell it the exact shape of the object. If you type it as object
, typescript cannot help you with that. Instead you could tell it the exact properties and datatypes the object has:
let assistance: { safe: string } = { safe: 1 /* typescript can now tell this is wrong */ };
assistance.unknown; // typescript can tell this wont really work too
Now in the case that the object can contain any sort of key / value pair, you can at least tell typescript what type the values (and the keys) have, by using an object index type:
items: {
[key: string]: number | string,
}[]
That would be the accurate type in the case given.
score:-14
try adding type any[]
items:any[]
score:9
First of all, defining the type of items
as an array of objects
is a bad idea, as it defeats the purpose of Typescript. Instead define what type of objects the array will contain. I would do it this way:
type Item = {
id: number,
name: string,
email: string,
}
export type TableGridViewProps = {
items: Item[],
tableColumns: TableColumn[]
};
After that if you're absolutely sure that the key
would exist in item
, you can do the following to tell Typescript that you are accessing a valid index.
<td
key={column.key}
className="lorem ipsum"
>
{item[column.key as keyof typeof Item]}
</td>
score:12
Use Generics
// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
obj[key];
Bad - the reason for the error is the object
type is just an empty object by default. Therefore it isn't possible to use a string
type to index {}
.
Better - the reason the error disappears is because now we are telling the compiler the obj
argument will be a collection of string/value (string/any
) pairs. However, we are using the any
type, so we can do better.
Best - T
extends empty object. U
extends the keys of T
. Therefore U
will always exist on T
, therefore it can be used as a look up value.
Here is a full example:
I have switched the order of the generics (U extends keyof T
now comes before T extends object
) to highlight that order of generics is not important and you should select an order that makes the most sense for your function.
const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
obj[key];
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
const getUserName = getKeyValue<keyof User, User>("name")(user);
// => 'John Smith'
score:12
If it's a pedantic javascript object that doesn't make sense to create type definitions per field for, and doesn't make sense as a class definition, you can type the object with any
and typescript will let you index however you want.
ex.
//obviously no one with two brain cells is going to type each field individually
let complicatedObject: any = {
attr1: 0,
attr2: 0,
...
attr999: 0
}
Object.keys(complicatedObject).forEach(key => {
complicatedObject[key] += 1;
}
Source: stackoverflow.com
Related Query
- react typescript error - element implicitly has an any type because expression of type string cant be used to index type {}
- string can't be used to index type '{ firstName: { inputWarning: string; inputRegex: RegExp; };
- React-Typescript, redux toolkit - expresion of type string can`t be used to index type'Writable Draft'
- 'string' can't be used to index type '{}'
- Type 'undefined' cannot be used as index type
- Type Check help on Object with string index
- TS | Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Record<SecurityMode, boolean>'
- Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
- TypeScript Err: "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type
- Cant start React simple app I get Error: Element type is invalid: expected a string
- Is Missing in Type {}, but Required in Type ' ' & ' ' Is not Assignable to String Index Type ' ' Errors
- Type '() => Promise<AxiosResponse<any>>' cannot be used as an index type [ReactJs]
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Palette'
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type React Typescript
- Type 'String' cannot be used as an index type when adding key/val pair to object
- Typescript: Type 'undefined' cannot be used as an index type.ts(2538)
- Type 'undefined' cannot be used as an index type.ts(2538)
- Typescript error Type 'undefined' cannot be used as an index type
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{...}'
- Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Breakpoints'
- how fix Element implicitly has an 'any' type because expression of type 'string' can't be used to index type?
- TypeScript - Element implicitly has an 'any' type because expression of type '"storyFile"' can't be used to index type '{}'
- cannot be used as a JSX component Its return type string | Element is not a valid JSX element Type 'string' is not assignable to type 'Element | null'
- Typescript Error: Expression of type 'string' can't be used to index type
- Type 'undefined' cannot be used as an index type
- Property 'country' does not exist on type 'never' and type 'string' can't be used to index type '{}'
- Typescript with React > Element implicitly has an 'any' type because expression of type 'string' can't be used to index
- Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'Item'
- Nested Object -> Element implicitly has an 'any' type because expression of type 'string' can't be used to index type
More Query from same tag
- ReactJS: fetch from api print not just one time
- React js backend how to get the price_data info from stripe.checkout.session.line_items and push the data into firestore
- React How to Filter Data Array using Multiple Checkbox
- Compiling React with Webpack 4.x and Babel 8.x
- How to svg morph in ReactJs between two elements
- Material-UI : How to properly set userAgent for server-side rendering
- How can I use a button to change the Theme for material UI on my site? this is where I am so far
- correct way to call GraphQL mutation from react using hooks
- React router force to another page if a variable doesn't exist
- React - objects are not valid as a React child
- TypeError: Class extends value #<Object> is not a constructor or null in react js
- Preflight CORS error followed by 404 error
- React JS : Yup & Formik Error Message showing multiple times on Submit
- How to toggle checkbox value in React Hooks?
- React without Webpack
- Radio button with label align vertical
- Typescript React generic function type
- Why couldn't my gulp work
- React-Router-Dom: Make Home The Landing Page
- How to keep cursor position in a react input element
- react-redux: understanding communication between Provider and representational components
- Combine navigation and footer routes into one place
- Making request parameter optional in axios get request
- How to reload the Data of a child when a child Component is being rendered in ReactJs
- Can't access array in nested immutable object
- React Router + Redux?
- React useState sets response from database but when I try to access the data[0].listing_reviews it returns an undefined error
- How to create a refresh button with 4 different data end points in React?
- how to filter array object using object property
- Dig into an object to meets a condition and returns the property that is levels above