Skip to content

Commit

Permalink
docs: typescript guide (#3)
Browse files Browse the repository at this point in the history
Co-authored-by: wibus-wee <[email protected]>
  • Loading branch information
AkaraChen and wibus-wee authored Dec 20, 2022
1 parent 300bf95 commit 78cdc05
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
7 changes: 6 additions & 1 deletion docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,12 @@ export default defineConfig({
text: 'Writing JSX',
link: '/jsx/writing-jsx',
}]
}
},
{
text: 'Publish component library', items: [{
text: 'TypeScript',
link: '/publish/typescript'
}]}
]
},

Expand Down
54 changes: 54 additions & 0 deletions docs/publish/typescript.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# TypeScript

## The why

When you define a web components, TypeScript doesn't know anything about it, all the props will be `any` type. Unless you define it.

## Define for TypeScript

```ts
@JwcComponent({ name: "app-element" })
export class App extends JwcComponent {
@Prop() name: string = "World";
override render() {
return <div>{this.name}</div>;
}
}

declare global { // [!code focus]
interface HTMLElementTagNameMap { // [!code focus]
"app-element": App; // [!code focus]
} // [!code focus]
} // [!code focus]
```

Then, you can get full type intelligence on this component:

```ts
// Auto complete component name.
const app = document.createElement('app-element')
// Will get type error in IDE.
app.name = 1
```

## Define for TSX

In `.tsx`, your component will perform well, but still get type error, becasue jsx compiler have it's own type defination.

Add following code to fix it.

```ts
type Reactify<T> = Partial<T> &
React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>;

declare global {
namespace JSX {
interface IntrinsicElements {
'app-element': Reactify<App>;
}
}
}
```

0 comments on commit 78cdc05

Please sign in to comment.