type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

NonNegativeInteger doesn't work

Open GregJArnold opened this issue 1 year ago • 3 comments

When I define a React component as follows:

import {NonNegativeInteger} from "type-fest";

interface ReactComponent {
  trim?: NonNegativeInteger<number>;
}

And use it in the component:

<ReactComponent trim={2} />

I get the following error:

TS2322: Type 'number' is not assignable to type 'undefined'.
    28 | 			{title && url ? (
    29 | 				<a className={styles.link} href={url} target="_blank" rel="noopener noreferrer">
  > 30 | 					<ReactComponent size={1} trim={2}>
       | 					               ^^^^
    31 | 						{title}
    32 | 					</ReactComponent>
    33 | 				</a>

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar

GregJArnold avatar Mar 08 '23 14:03 GregJArnold

You are not preserving the input literal type.

It should be something like:

interface ReactComponent<T extends number> {
  trim?: NonNegativeInteger<T>;
}

sindresorhus avatar Mar 08 '23 16:03 sindresorhus

That doesn't make any sense. I'd be backing up the T extends number to the interface for the React component, which would change nothing (and still gives the same error). My use case is, as I showed, to have a React component that can take a prop that is any non-negative integer.

GregJArnold avatar Mar 08 '23 16:03 GregJArnold

declare size prop ?

liuhanqu avatar Mar 09 '23 01:03 liuhanqu

It seems that NonNegativeInteger is meant to be used as a function parameter only:

https://github.com/sindresorhus/type-fest/blob/f19a002f728c14302191020bfc399b4eb6950abf/source/numeric.d.ts#L185-L205

You might want to ask on StackOverflow how to cause const n: NonNegativeNumber = -1 to throw an error, but I don’t think what you're asking is possible.

fregante avatar Aug 13 '24 17:08 fregante