避免使我的代码臃肿,reactjs,typescript,react-native"/>

首页 > 解决方案 > TypeScript 和 React Native:使用 Pick避免使我的代码臃肿

问题描述

我有以下接口和使用它的 React Native 组件:

import { KeyboardTypeOptions, TextInputProps } from 'react-native';
import { TextInput } from 'react-native-paper';

export interface ValidatedInputProps {
    autoCapitalize?: 'none' | 'sentences' | 'words' | 'characters',
    contentType: Pick<TextInputProps, 'textContentType'>,
    isSecure?: boolean,
    keyboard?: KeyboardTypeOptions,
    label: string,
}

export const ValidatedInput = ({
    autoCapitalize = 'none',
    contentType,
    isSecure = false,
    keyboard = 'default',
    label,
}: ValidatedInputProps) => {
    return (
        <TextInput
            textContentType={contentType} <-- Error is flagged here
            ...other props
        />
    );
};

这给了我在 VSCode 中的以下错误弹出窗口:

Type 'Pick<TextInputIOSProps, "textContentType">' is not assignable to type '"none" | "name" | "URL" | "addressCity" | "addressCityAndState" | "addressState" | "countryName" | "creditCardNumber" | "emailAddress" | "familyName" | "fullStreetAddress" | ... 17 more ... | undefined'.
  Type 'Pick<TextInputIOSProps, "textContentType">' is not assignable to type '"oneTimeCode"'.ts(2322)
index.d.ts(1250, 5): The expected type comes from property 'textContentType' which is declared here on type 'IntrinsicAttributes & Pick<TextInputProps, "textContentType" | "clearButtonMode" | "clearTextOnFocus" | "dataDetectorTypes" | "enablesReturnKeyAutomatically" | ... 114 more ... | "dense"> & { ...; } & { ...; }'
(JSX attribute) textContentType?: "none" | "name" | "URL" | "addressCity" | "addressCityAndState" | "addressState" | "countryName" | "creditCardNumber" | "emailAddress" | "familyName" | "fullStreetAddress" | ... 17 more ... | undefined

我显然完全误解了该Pick<T, K>类型的意义,但我在过去两个小时内阅读的关于该主题的所有内容似乎都暗示我的用法是正确的。那么我错过了什么?

我想我可以contentType用正确的联合来定义我的道具(就像我对 所做的那样autoCapitalize),但是当它已经在其他地方定义时,谁会想要用过长的字符串来膨胀他们的代码呢?!我不能只导入该属性/类型并完成它吗?

标签: reactjstypescriptreact-native

解决方案


选择<类型,键>

通过从 中选择一组属性Keys(字符串文字或字符串文字的并集)来构造一个 Object 类型Type

因此,它不是为您提供允许值textContentType的联合,而是为您提供具有单个键的 Object 类型textContentType

相反,您可以使用您需要的属性扩展Picked版本TextInputProps,然后将您自己的属性添加到接口中。

import { KeyboardTypeOptions, TextInputProps } from 'react-native';

interface ValidatedInputProps extends Pick<TextInputProps, 'textContentType' | 'autoCapitalize'>  {
  isSecure?: boolean,
  keyboard?: KeyboardTypeOptions,
  label: string,
}

或者,您可以通过从导入的 Object 类型访问每个已知属性来创建本地类型。

import { KeyboardTypeOptions, TextInputProps } from 'react-native';

type myTextContentType = TextInputProps['textContentType']
type myAutoCapitalize = TextInputProps['autoCapitalize']

interface ValidatedInputProps {
  textContentType?: myTextContentType,
  autoCapitalize?: myAutoCapitalize,
  isSecure?: boolean,
  keyboard?: KeyboardTypeOptions,
  label: string,
}

推荐阅读