简体   繁体   中英

TypeScript: How can I fix a type issue with using `.length` to count the characters or a component's `children`?

I have the following code to count the length of text within my component's children and add a class:

className={clsx(classes.text, {
   [classes.textSmall]: children?.length ?? 0 > 11,
})}

This works but I get a TypeScript error on .length .

Property 'length' does not exist on type 'number'.ts(2339)

I am not sure how to address this as children don't really have type.

Would anyone know what I should be doing?

It seems like your children is of type number , and you're trying to find its length. This fails as there is no .length property on number . You can get around this by converting this to a string first, and then checking its length like so:

className={clsx(classes.text, {
   [classes.textSmall]: (`${children}`)?.length ?? 0 > 11,
})}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM