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.
@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? |
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.