score:1
you can't use destructuring of union of interfaces and expect ts to discriminate which interface is the relevant one at runtime.
you also can't use typeof
or instanceof
at runtime to dynamically infer it yourself.
what you could do is destructuring all attributes by casting props object to some interface and extract the relevant attributes each time, something like:
const element: react.fc<icommon> = props => {
const {name, age} = props as ifirst;
const {cars, friends} = props as isecond;
return (...);
}
please notice that you cannot declare name
twice in the same scope, so i declared it only once...
if you want to be sure which type you're dealing with, you could determine the 'actual' type without any warnings using casting:
if ((props as isecond).cars !== undefined) {
const {name, cars, friends} = props as isecond;
}
same goes with age
and ifirst
.
if you want to do a little better practice - there is an article i found about discriminated unions and destructuring in typescript.
another way is to 'add' your props object's type the desired attributes using the is
keyword, while also determining the actual type of your props:
function hascars(obj: any): obj is isecond {
return !!obj && typeof obj === "object" && "cars" in obj;
}
function hasage(obj: any): obj is ifirst {
return !!obj && typeof obj === "object" && "age" in obj;
}
const element: react.fc<icommon> = (props) => {
if (hascars(props)) {
// props is now exactly of type isecond
const {name, cars, friends} = props; // this is a valid statement now
props.friends // also won't cause the red line...
}
else if (hasage)) {
// same here but with ifirst
}
}
Source: stackoverflow.com
Related Query
- Use typescrip iterfaces in react js application
- What are the scenarios one should use isRequired for PropType vs defaultProps in React Application
- How do I properly use ASP.NET Core Web Application React project template
- Use PrimeReact Themes with CSS Modules Enabled in React Application
- Unable to use material-ui-pickers in React js web application
- How to use React component in Angular 6 application
- how to use angular 6 component in react application
- How to Use AWS Amplify react components anywhere in an application
- why my react application got crash even when i use Error Boundaries?
- How to use Google fonts in a React application using Next.js
- How to use react as a component library rather than application
- React Dev Tools - Unable to use profiler in Electron application
- How to use TempData in ASP.NET Core React application
- Is it possible use aws-amplify without cognito in react web application
- modifying dotnetify react js to use in cordova application (change path of dotnetify.react.connect)
- Production build of React application showing trimmed componentStack when I use componentDidCatch
- Can't create a React component in node_modules and use it in an application
- How to use React Router properly? I am trying to push the state of my application to another page when the user logs in
- When to use Dispatcher in React Application
- Right way to use react router v4 in the react application
- How to use a federated React module if the host React application isn't using Webpack?
- how to use bootstrap.min.js in react 4 application
- Use same instance of socket across React application
- Laravel and react, How to give a notification from Laravel to my react application (Unexpected use of 'self' no restricted-globals error)
- Use setInterval and recurcive setTimeout in SPA React application without memory leaks
- how to honor windows use from React js front end application when node js api is used
- How can we configure dotnet core react application to use mulltientry?
- How to use componentWillMount() in React Hooks?
- When to use ES6 class based React components vs. functional ES6 React components?
- How to use `setState` callback on react hooks
More Query from same tag
- React Ant Design styles not loading
- "Hooks can only be called inside of the body of a function component" even it's inside a function component
- Import a selfcalling function from an npm module into a react/webpack app
- How to convert Excel file being pass as XML from server to JavaScript(React)
- undefined values on post method from react app
- How to retrieve data in PHP, sent from React js using fetch()?
- React route exact not work if I have child route in React router v5
- React - TypeError: Cannot read property 'push' of undefined, already exported default withRouter
- Handling Redux Saga result in view from which action call originates
- Highcharts error missing ModuleFor=arearange
- typescript how to omit enum values
- Formik: Why setTimeOut in onSubmit?
- Use Error() without throwing exception in Jest
- User roles: node.js express sequelize react.js
- Unexpected token when using multiple punctuations
- How do I enable touch on multiple buttons simultaneously in react native?
- Can I use react in some view of my laravel website
- Testing popover components with testing-library for react
- Random quote button works only once on clicking
- Getting one data at table row
- React mapped state text rendered as is
- Disable link on ant design form submit
- Change the background image dynamically
- How to resolve this `t9n` translations error when I use its `plural` property?
- Is there a way to halt loading a react app until authentication status is resolved?
- validate.js validating arrays
- How to describe extracted values to an array in typescript
- How to store multiple values under the same field on Firestore?
- Only one element of type cardNumber can be created
- Multiple validations on React PropTypes