简体   繁体   中英

Input types in Typescript interface

I'm trying to write a component to reuse and one of the varibles is the input type to render.

Currently, I have this:

type InputBaseProps = {
  children?: ReactChild;
  className?: string;
  id: string;
  label?: string;
  name?: string;
  onBlur: (event: ChangeEvent<HTMLInputElement>) => void;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  style?: CSSProperties;
  type: ????;
  value?: string;
};

I want to allow only valid HTML types , like the entire list defined here https://www.w3schools.com/tags/att_input_type.asp

Is there any simple way to do it?

Yes it is simple, you just put | between all the types you want. For example it would be like so

"button" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "image" | "month" | "number" | "password" | "radio" | "range" | "reset" | "search" | "submit" | "tel" | "text" | "time" | "url" | "week"

These were all grabbed from the w3schools page you listed

Please accept this if this fits your needs

Create an exportable enum ...

export enum InputType {
    button = "button",
    checkbox = "checkbox",
    color = "color",
    date = "date",
    datetimelocal = "datetime-local",
    email = "email",
    file = "file",
    hidden = "hidden",
    image = "image",
    month = "month",
    number = "number",
    password = "password",
    radio = "radio",
    range = "range",
   reset = "reset",
    search = "search",
    submit = "submit",
    tel = "tel",
    text = "text",
    time = "time",
    url = "url",
    week = "week"
};

Then you can do ...

type InputBaseProps = {
  children?: ReactChild;
  className?: string;
  id: string;
  label?: string;
  name?: string;
  onBlur: (event: ChangeEvent<HTMLInputElement>) => void;
  onChange: (event: ChangeEvent<HTMLInputElement>) => void;
  placeholder?: string;
  style?: CSSProperties;
  type: String as () => InputType;
  value?: string;
};

Then using it ...

import {InputType} from './file-your-enum-is-in';
const el: InputBaseProps  = {
    ...
    type: InputType.text,
    ...
};
import { HTMLInputTypeAttribute } from "react";

type InputBaseProps = {
    type?: HTMLInputTypeAttribute 
}

HTMLInputTypeAttribute resolves to the ff:

type HTMLInputTypeAttribute = "number" | "search" | "button" | "time" | "image" | "text" | "checkbox" | "color" | "date" | "datetime-local" | "email" | "file" | "hidden" | "month" | "password" | "radio" | "range" | ... 5 more ... | (string & {})

Intellisense working fine.

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