DEV Community

Discussion on: Default Props in React/TypeScript

Collapse
 
jwp profile image
JWP • Edited

Adam,

From this.

interface Props extends PropsWithChildren<any>{
   requiredString: string,
   requiredNumber: number,
   optionalBoolean?: boolean,
   optionalString?: string,
   optionalNumber?: number,
}

export default function MyTSComponent(props: Props) {
   props.optionalBoolean = props.optionalBoolean !== undefined ? props.optionalBoolean : true;
   props.optionalString = props.optionalString !== undefined ? props.optionalString : 'yo';
   props.optionalNumber = props.optionalNumber !== undefined ? props.optionalNumber : 42;
   console.log(props);
   return (
      <>
         Here is MyComponent:<br/>
         {props.children}
      </>
   );
}

To this?

// props is still an interface but it has behaviors as a class
class Props extends PropsWithChildren<any>{
  constructor(props)
   requiredString: string = props.optionalString !== undefined ? props.optionalString : 'yo';
   requiredNumber: number =props.optionalNumber !== undefined ? props.optionalNumber : 42;
   optionalBoolean?: boolean =props.optionalBoolean !== undefined ? props.optionalBoolean : true;

}


export default function MyTSComponent(props: Props) {

   console.log(props);
   return (
      <>
         Here is MyComponent:<br/>
         {props.children}
      </>
   );
}

Here's two possible examples:

//  I think this may work.
export default function MyTSComponent(props: Props) {

// But, this always work
export default function MyTSComponent(props) {
  let properties : props = new Props(props);

There is another way to cast Javascript into TS types. Like this:

//but this bypasses the ctor logic
let newtype:Props = props;
// so we redesign the Props class.
// meaning always initilize with default values, except for optional props.
class Props extends PropsWithChildren<any>{ 
   requiredString: string =  'yo';
   requiredNumber: number  42;
   optionalBoolean?: boolean;  
}


A number of javascript folks don't like the new keyword, no problem create a factory...


export function CreatedProps(props){
  return new Props(props);

Collapse
 
jwp profile image
JWP

Ok Adam, updated my response.

Collapse
 
bytebodger profile image
Adam Nathaniel Davis

When I type:

class Props extends PropsWithChildren<any> {

}

The TS linter tells me that:

'PropsWithChildren' only refers to a type, but is being used as a value here.

Collapse
 
jwp profile image
JWP

Ok make that one a class too

Thread Thread
 
jwp profile image
JWP

Or change extends to implements.