-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Basic] Improve the class component defaultProps example #103
[Basic] Improve the class component defaultProps example #103
Conversation
In the current example, we have a type definition for props but do not make use of it for defaultProps. This can lead to a mismatch between defaultProps and props.
good eye! thanks very much! |
@sw-yx Actually, I just checked, and the caveat that is stated under "Typescript 2.9 and earlier" still applies - Another approach would be to use: static defaultProps: Pick<Props, 'name'> = { name: 'world' }` What do you think? |
A good way of working with type Props = typeof MyComponent.defaultProps & {
age: number
}
class MyComponent extends Component<Props> {
static defaultProps = {
name: 'world'
}
} |
o shit lets do that instead! much nicer. |
I ran into a case where the // in a separate file
interface ModelValues = {
title: string
description?: string
}
// in a custom formik form
type Props = {
onSubmit: (values: ModelValues, actions: FormikActions<ModelValues>) => void
initialValues: ModelValues
}
class ModelForm extends React.Component<Props> {
static defaultProps: Pick<Props, 'initialValues'> = {
initialValues: {
title: ''
description: ''
}
}
render() { ...}
} The reason I want to have a type definition directly on |
This has been merged, so not sure if y'all will see this, but: This seems to now be possible if you make use of an interface for props:
|
i see you @RiaanWest. wanna PR something? |
This will break export type IconSize = 'small' | 'regular' | 'medium' | 'large';
interface IconPropsInterface {
icon: string;
size?: IconSize;
}
export class Icon extends Component<IconPropsInterface> {
static defaultProps: IconPropsInterface = {
icon: '',
size: 'regularrr', <-- Throws: Type '"regularrr"' is not assignable to type '"small" | "regular" | "medium" | "large" | undefined'.ts(2322)
}
}
const myIcon = <Icon /> // this will not throw an error even though `icon` is required, |
Thanks for pointing this out @ferdaber - great point. I wasn't aware of that! |
What cheatsheet is this about? (if applicable)
Basic cheatsheet
--
In the current example, we have a type definition for
Props
but do not make use of it fordefaultProps
. This can lead to a mismatch between the actual fields indefaultProps
and what theProps
type defines.Adding an explicit
Partial<Props>
type todefaultProps
seems like good example code.