【问题标题】:React&Typescript Exclude from interface definitionReact&Typescript 从接口定义中排除
【发布时间】:2018-08-30 09:33:35
【问题描述】:

经过几个小时的测试,我问你。我想定义我的接口对象

export interface OptionPros {
    text: string;
    color?: string|undefined;
    fontStyle?: string|undefined;
    sidePadding?: number|undefined;
}

之后,我想创建一个只使用“文本”属性的类型,其他都是可选的。

type OO=Exclude<"color"|"fontStyle"|"sidePadding", OptionPros>

现在一切都好,但是当我尝试在我的班级的道具中使用这个定义时

file1.tsx

export interface OptionPros {
    text: string;
    color?: string|undefined;
    fontStyle?: string|undefined;
    sidePadding?: number|undefined;
}
type OO=Exclude<"color"|"fontStyle"|"sidePadding", OptionPros>

export interface DProps extends BaseProps {
    optionD: OO
}
export default class DDD <DProps> {
    static defaultProps = {
        optionD: {
            text: '',
            color: '#FF6384', // Default is #000000
            fontStyle: 'Arial', // Default is Arial
            sidePadding: 20 // Defualt is 20 (as a percentage)
        }
    };
    render() {<div>AAAA</div>}
 }

file2.tsx

 //i omit react and other inclusion or extension
 import.....
 export default class AAAA {
 render() {return(<DDD optionD={{text:"hello world"}}>AAAA</DDD >)}

我有这个消息错误

输入'{文本:字符串; }' 不可分配给类型 '{ text: string;颜色:字符串;字体样式:字符串;侧边距:数字; }'。 '{ text: string; 类型中缺少属性 'color' }'。

我不明白为什么?我使用 typescript > 2.8 anche ts 文档,它不是很清楚。有人可以帮助我解决和理解我的错误吗?

【问题讨论】:

    标签: reactjs typescript definition


    【解决方案1】:

    我相信我已成功重现该错误。你的组件声明应该是:

    export default class DDD extends React.Component<DProps> { ... }
    //                       ^^^^^^^^^^^^^^^^^^^^^^^
    

    如果您想从OptionPros 中排除colorfontStylesidePadding 属性,您需要的不是Exclude(它只是从另一种类型中排除一种),而是更常见的操作名为Omit,定义和使用如下:

    type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
    type OO=Omit<OptionPros, "color"|"fontStyle"|"sidePadding">
    

    通过这些更改,我不再收到错误消息。

    【讨论】:

    • 谢谢马特,但是选择什么?你能给我精确阅读的网址以了解 T,K e PIck
    • 有一些关于“实用程序类型”here 的文档。这个页面是最近添加的,我希望它最终会部署到typescriptlang.org/docs/handbook。有关如何定义这些类型的更多背景信息,请参阅 Mapped typesConditional types
    猜你喜欢
    • 1970-01-01
    • 2017-12-12
    • 2015-07-27
    • 2019-01-06
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多