Home > Blockchain >  How to customize an interface to one use on TypeScript
How to customize an interface to one use on TypeScript

Time:07-14

I have this code and I want to use the interface ILink on Link component, but I don't want to add linkType property always that I need to use the Link component. I want that the propriety linkType be default when I don't declare.

How can I do this?

My files:

index.ts

import { StyledLink, ILink } from './styled'

export default function Link(props: ILink) {
  const { href, children, linkType } = props

  return (
    <StyledLink href={href} linkType={!linkType ? 'default' : linkType}>
      {props.children ? (children) : (href)}
    </StyledLink>
  )
}

styled.ts:

export interface ILink {
  href: string
  linkType: 'default' | 'applications'
  children?: React.ReactNode
}

export const StyledLink = styled.a<ILink>`
 ...
`
```

CodePudding user response:

If I understood you correctly, you can achieve that in the following way:

Make the linkType property optional:

export interface ILink {
  href: string
  linkType?: 'default' | 'applications'
  children?: React.ReactNode
}

Then set 'default' as default value for linkType:

  const { href, children, linkType = 'default' } = props
  • Related