component-size icon indicating copy to clipboard operation
component-size copied to clipboard

TypeScript: constraint ref to element

Open OliverJAsh opened this issue 5 years ago • 2 comments

Previously this would not error at compile time:

import useComponentSize from '@rehooks/component-size';
import React = require('react');

declare const ref: React.RefObject<{ foo: 1 }>;
// No error
useComponentSize(ref);

With this change, it does.

useComponentSize always expects the ref to contain a HTML element, so it can reliably extract size/dimensions.

OliverJAsh avatar May 01 '19 16:05 OliverJAsh

  • I think Element is a strong enough constraint, allowing it to continue to work on SVG elements

Will fix

2. you can still keep it generic with T extends Element instead of removing the generic altogether

This function doesn't need to be generic, because the generic is only used for one parameter and it's not used in the return type.

Type parameters, that are only used once in the entire signature and don't have a constraint that contains another type parameter, are useless. They don't add type safety to the signature and can simply be replaced by their constraint or any if there is none.

https://github.com/fimbullinter/wotan/blob/def90abb18a3736d7b177a9f9a0b9b624b302f3a/packages/mimir/docs/no-misused-generics.md

https://twitter.com/SeaRyanC/status/1118634571564630016

OliverJAsh avatar Mar 04 '20 13:03 OliverJAsh

@osdiab Done

OliverJAsh avatar Mar 04 '20 13:03 OliverJAsh