TSX: Props type definition for a number input - javascript

In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is InputHTMLAttributes:
interface InputHTMLAttributes<T> extends HTMLAttributes<T> {
accept?: string;
alt?: string;
autoComplete?: string;
autoFocus?: boolean;
capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute
checked?: boolean;
crossOrigin?: string;
disabled?: boolean;
form?: string;
formAction?: string;
formEncType?: string;
formMethod?: string;
formNoValidate?: boolean;
formTarget?: string;
height?: number | string;
list?: string;
max?: number | string;
maxLength?: number;
min?: number | string;
minLength?: number;
multiple?: boolean;
name?: string;
pattern?: string;
placeholder?: string;
readOnly?: boolean;
required?: boolean;
size?: number;
src?: string;
step?: number | string;
type?: string;
value?: string | ReadonlyArray<string> | number;
width?: number | string;
onChange?: ChangeEventHandler<T>;
}
I want to define a specific type for only an input of type number so that TypeScript complains if I use a checked or disabled prop on it:
<!-- invalid `checked` prop -->
<input type="number" step="any" min="0" max="100" value="22.33" checked={true} />
So is there already a type definition for that coming from React?
I know that I can just define it like the following but I would prefer to use an official source:
interface InputNumberProps {
type: 'number';
max?: number | string;
min?: number | string;
...
}

I think the simplest solution would be to wrap input into your own component and provide custom type definitions. As far as I know, there is nothing like that coming from official React types. This is done because HTML itself is not strongly typed and it is valid to do something like <input type="number" checked />
As for type definition something like that would suffice:
interface NumberInputProps {
type: "number"
value: number
min?: number
max?: number
}
interface TextInputProps {
type?: "text"
value: string
}
interface CheckboxInputProps {
type: "checkbox"
checked?: boolean
}
type InputProps = NumberInputProps | TextInputProps | CheckboxInputProps
const Input: React.FC<InputProps> = (props) => <input {...props} />
That is a lot of typings for sure (and this does not event include things like events, class names etc). Also, this requires even more JS code if you want to provide stronger types for something like number fields (converting strings into numbers etc.)
If you want to modify the original InputHTMLAttributes (which is a better solution than writing your own types from scratch) interface, overriding and/or omitting some of the fields there are helper types like Omit that would allow you to do so.
type InputProps = Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "checked" | "min" | "max"> & (NumberInputProps | TextInputProps | CheckboxInputProps)
You can also split different input types into different components if you find writing too much logic in one component. Do whatever suits you
P.S. on the second note. This sounds like type over-engeneering

You can use and extends the official types:
export type InputProps = React.DetailedHTMLProps<
React.InputHTMLAttributes<HTMLInputElement>,
HTMLInputElement
>;
interface NumberInputProps extends Omit<InputProps, 'checked' | 'disabled'> {
value: number
}
Using this code you exclude checked and disabled properties and overrides value to allow only numbers instead string | ReadonlyArray | number

Related

Get interface that can have multiple query responses in GraphQL

Currently in my GraphQL query, i can receive a single array response. But my response can be multiple arrays and there can be null in between of the response too depending on the input. Currenly if i have two inputs and suppose i'm getting an array for the first input and error for the second, it will throw an error. I need to fix that by showing null if error and returning the array if success. Here's what i have right now:
export const LookupUsers = gql`
query {
lookupUsers(ethAddresses: ["0x433232bC8C604d0308B71Defdgd1Da86"]) {
...User
}
}
fragment Identifiable on Node {
__typename
id
}
fragment User on User {
...Identifiable
ethAddress
firstName
lastName
}
`;
export interface Result {
readonly user: null | Array<null | User> ;
readonly lookupUsers: Array<null | LookupUsersType>;
}
export interface LookupPayload {
readonly payload: Array<string>;
}
export interface User extends Identifiable {
readonly ethAddress: string;
readonly emailAddress?: string;
readonly firstName?: string;
readonly lastName?: string;
}
export interface LookupUsersType extends Identifiable {
readonly ethAddress: string;
readonly emailAddress: string;
readonly firstName?: string;
readonly lastName?: string;
}
export interface Identifiable {
readonly __typename: string;
readonly id: string;
}
Where am i going wrong with this ?

TypeScript error with Symbol.species example from MDN

With this code (which is equivalent to a sample at MDN):
class MyArray<T> extends Array<T> {
static get [Symbol.species]() { return MyArray }
}
I get this error (with TypeScript 3.8.3):
Class static side 'typeof MyArray' incorrectly extends base class static side '{ isArray(arg: any): arg is any[]; readonly prototype: any[]; from<T>(arrayLike: ArrayLike<T>): T[]; from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[]; from<T>(iterable: Iterable<...> | ArrayLike<...>): T[]; from<T, U>(iterable: Iterable<...> | ArrayLike<...>, mapfn: (v: T, k: nu...'.
Types of property '[Symbol.species]' are incompatible.
Type 'typeof MyArray' is not assignable to type 'ArrayConstructor'.
Type 'typeof MyArray' provides no match for the signature '(arrayLength?: number | undefined): any[]'.
What could be wrong?

Subclass method signature inference

I have the following abstract class
// AbstractFiller.ts
export abstract class AbstractFiller {
public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}
and several filler subclasses
export class WhiteSpacesFiller extends AbstractFiller {
public fill(data: number | string | boolean | Date, numberOfFillers: number): string {
// logic
}
}
export class ZerosFiller extends AbstractFiller {
public fill(data: number | string | boolean | Date, numberOfFillers: number): string {
// logic
}
}
// ...etc
Is there a way that TS would infer the method signature from the abstract class so that I have:
No type duplication in every subclass
Strict signature enforcing e.g. removing number from the type of data in a subclass will not throw an error.
Typescript will not infer method parameters from base class. The way it works is that after the class is typed, the class is checked for compatibility with the base class. This mean that a parameter in a derived class can be of a derived type (this is not sound but class method parameters relate bivariantly even under strict null checks).
One thing that can be done to reduce the amount of type duplication is to use Parameters with rest parameter destructuring.
export abstract class AbstractFiller {
public abstract fill(data: number | string | boolean | Date, numberOfFillers: number): string;
}
export class WhiteSpacesFiller extends AbstractFiller {
public fill(...[data, numberOfFillers]: Parameters<AbstractFiller['fill']>): string {
return ""
}
}
Excuse me if I misunderstand the question, but I think you can solve your problem with generics i.e. have your AbstractFiller class be generic.
That would look something like this:
export abstract class AbstractFiller<T> {
public abstract fill(data: T, numberOfFillers: number): string;
}
export class WhiteSpacesFiller extends AbstractFiller<string> {
public fill(data: string, numberOfFillers: number) {
//logic
return data;
}
}
export class ZerosFiller extends AbstractFiller<number> {
public fill(data: number, numberOfFillers: number) {
return data.toString();
}
}

Assign #Input() object properties to the component

I am having an Angular component with a single #Input element:
#Input('member') member: Member;
the Member interface looks like this:
export interface Member {
name: string;
surname: string;
display_name: string;
positions: number[];
image_url: string;
email: string;
address: string;
office_phone: string;
phone: string;
whatsapp: string;
skype: string;
}
I want to access the member fields from html template like {{ name }}, {{ email }} etc...
wtihout prefixing each of them.
For example, I do not want to access these properties like {{ member.name }}, {{ member.email }}, I like the shortcut version.
The component will have only a single #Inpurt property - the Member object.
Is there a nice way to reassign the member. properties to the Angular component? Or any other way to use a shortcut, I mensioned above?
Not a good practice, but you should spread that object into your component :
ngOnInit() {
Object.entries(this.member).forEach(([key, value]) => this[key] = value);
// OR
Object.assign(this, this.member);
}
You can now use them as if they were class properties. Be warned that it will override any other property with the same name on your class, so you should be careful about that solution and instead use member.XXX.

How to extend a TypeScript interface and unpartial it

I want to be able to do the following:
interface Partials {
readonly start?: number;
readonly end?: number;
}
interface NotPartials extends Partials /*incorporate Unpartialing somehow */ {
readonly somewhere: number;
}
Then, NotPartials would be:
readonly start: number;
readonly end: number;
readonly somewhere: number;
Notice how start and end are required now. Is this possible anyway?
Well, this is silly.
I think in TypeScript 2.8 this is possible:
interface Partials {
readonly start?: number;
readonly end?: number;
}
interface NotPartials extends Required<Partials> {
readonly somewhere: number;
}

Categories

Resources