Skip to content

Commit 78cdc05

Browse files
AkaraChenwibus-wee
andauthored
docs: typescript guide (#3)
Co-authored-by: wibus-wee <[email protected]>
1 parent 300bf95 commit 78cdc05

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

docs/.vitepress/config.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,12 @@ export default defineConfig({
7878
text: 'Writing JSX',
7979
link: '/jsx/writing-jsx',
8080
}]
81-
}
81+
},
82+
{
83+
text: 'Publish component library', items: [{
84+
text: 'TypeScript',
85+
link: '/publish/typescript'
86+
}]}
8287
]
8388
},
8489

docs/publish/typescript.md

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# TypeScript
2+
3+
## The why
4+
5+
When you define a web components, TypeScript doesn't know anything about it, all the props will be `any` type. Unless you define it.
6+
7+
## Define for TypeScript
8+
9+
```ts
10+
@JwcComponent({ name: "app-element" })
11+
export class App extends JwcComponent {
12+
@Prop() name: string = "World";
13+
override render() {
14+
return <div>{this.name}</div>;
15+
}
16+
}
17+
18+
declare global { // [!code focus]
19+
interface HTMLElementTagNameMap { // [!code focus]
20+
"app-element": App; // [!code focus]
21+
} // [!code focus]
22+
} // [!code focus]
23+
```
24+
25+
Then, you can get full type intelligence on this component:
26+
27+
```ts
28+
// Auto complete component name.
29+
const app = document.createElement('app-element')
30+
// Will get type error in IDE.
31+
app.name = 1
32+
```
33+
34+
## Define for TSX
35+
36+
In `.tsx`, your component will perform well, but still get type error, becasue jsx compiler have it's own type defination.
37+
38+
Add following code to fix it.
39+
40+
```ts
41+
type Reactify<T> = Partial<T> &
42+
React.DetailedHTMLProps<
43+
React.HTMLAttributes<HTMLDivElement>,
44+
HTMLDivElement
45+
>;
46+
47+
declare global {
48+
namespace JSX {
49+
interface IntrinsicElements {
50+
'app-element': Reactify<App>;
51+
}
52+
}
53+
}
54+
```

0 commit comments

Comments
 (0)