-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: wibus-wee <[email protected]>
- Loading branch information
Showing
2 changed files
with
60 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>; | ||
} | ||
} | ||
} | ||
``` |