简体   繁体   English

React&Typescript从接口定义中排除

[英]React&Typescript Exclude from interface definition

after many hours of test i ask you. 经过数小时的测试,我问你。 i want define my interface object 我想定义我的接口对象

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

after, i will want create a type that use only "text" property, the other are optional. 之后,我将要创建一个仅使用“文本”属性的类型,其他是可选的。

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

now it's all ok, but whe i try use this definition in props of my class react 现在都可以了,但是当我尝试在班级的道具中使用这个定义时

file1.tsx 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 file2.tsx

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

and i have this messagge error 我有这个消息错误

Type '{ text: string; 输入'{text:string; }' is not assignable to type '{ text: string; }'不可指定为'{text:string; color: string; 颜色:字符串; fontStyle: string; fontStyle:字符串; sidePadding: number; sidePadding:数字; }'. }”。 Property 'color' is missing in type '{ text: string; 类型'{text:string;类型中缺少属性'color'。 }'. }”。

i can not understand why? 我不明白为什么? i use typescript > 2.8 anche the ts documentation it's not very clear. 我使用打字稿> 2.8和ts文档不是很清楚。 Can someone help me to resolved and undestand my errors? 有人可以帮助我解决和理解我的错误吗?

I believe I've succeeded in reproducing the error. 我相信我已经成功地重现了该错误。 Your component declaration should be: 您的组件声明应为:

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

And if you want to exclude the color , fontStyle , and sidePadding properties from OptionPros , what you need is not Exclude (which just excludes one type from another) but the operation more commonly called Omit , defined and used as follows: 而且,如果要从OptionPros排除colorfontStylesidePadding属性, OptionPros不需要的是Exclude (它只是将一种类型与另一种类型排除在外),而是通常称为Omit的操作,其定义和使用方式如下:

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

With these changes, I am no longer getting the error. 通过这些更改,我不再遇到错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM