[
  {
    "path": "contributing.md",
    "content": "# Contribution Guidelines\n\nFrom opening a bug report to creating a pull request: every contribution is appreciated and welcome."
  },
  {
    "path": "license",
    "content": "MIT License\n\nCopyright (c) 2017 Jason Wilson <jason@scurker.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE."
  },
  {
    "path": "readme.md",
    "content": "# Preact and Typescript\n\n> Some simple examples demonstrating how Typescript and Preact can work together. :heart:\n\n## Table of Contents\n\n1. [Setup](#setup)\n\t1. [Install Dependencies](#install-dependencies)\n\t2. [Setup tsconfig](#tsconfigjson)\n\t3. [Setup webpack config](#webpackconfigjs)\n2. [Stateful Components](#stateful-components)\n3. [Functional Components](#functional-components)\n4. [Components With Children](#components-with-children)\n5. [Higher Order Components (HOC)](#higher-order-components-hoc)\n6. [Extending HTML Attributes](#extending-html-attributes)\n7. [Rendering](#rendering)\n8. [Custom Elements / Web Components](#custom-elements--web-components)\n\n## Setup\n\n### Install Dependencies\n\n```bash\n$ npm install --save preact typescript webpack ts-loader\n```\n\n### tsconfig.json\n\n```json\n{\n  \"compilerOptions\": {\n    \"sourceMap\": true,\n    \"module\": \"commonjs\",\n    \"target\": \"es5\",\n    \"jsx\": \"react\",\n    \"jsxFactory\": \"h\"\n  },\n  \"include\": [\n    \"./src/**/*.tsx\",\n    \"./src/**/*.ts\"\n  ]\n}\n```\n\nIt's important to note the usage of `jsx: \"react\"` and `jsxFactory: \"h\"`. There are [several options available](https://www.typescriptlang.org/docs/handbook/jsx.html#basic-usage) for `jsx` that determine how Typescript outputs JSX syntax. By default without `jsxFactory: \"h\"`, Typescript will convert JSX tags to `React.createElement(...)` which won't work for Preact. Preact instead uses `h` as its JSX pragma, which you can read more about at [WTF is JSX](https://jasonformat.com/wtf-is-jsx/).\n\n### webpack.config.js\n\n```\nvar path = require('path');\n\nmodule.exports = {\n  devtool: 'source-map',\n  entry: './src/app',\n  output: {\n    path: path.resolve(__dirname, 'dist'),\n    filename: 'app.js'\n  },\n  resolve: {\n    extensions: ['.ts', '.tsx']\n  },\n  module: {\n    loaders: [\n      {\n        test: /\\.tsx?$/,\n        exclude: /node_modules/,\n        loaders: ['ts-loader']\n      }\n    ]\n  }\n}\n```\n\n> TODO: document webpack config\n\n## Stateful Components\n\nStateful components are Preact components that use any combination of state and/or [lifecycle methods](https://preactjs.com/guide/api-reference#lifecycle-methods).\n\n```jsx\nimport { h, Component } from 'preact';\n\nexport interface Props {\n  value: string,\n  optionalValue?: string\n}\n\nexport interface State {\n  useOptional: boolean\n}\n\nexport default class StatefulComponent extends Component<Props, State> {\n\n  constructor() {\n    super();\n    this.state = {\n      useOptional: false\n    };\n  }\n\n  componentWillMount() {\n    fetch('/some/api/')\n      .then((response: any) => response.json())\n      .then(({ useOptional }) => this.setState({ useOptional }));\n  }\n\n  render({ value, optionalValue }: Props, { useOptional }: State) {\n    return (\n      <div>{value} {useOptional ? optionalValue : null}</div>\n    );\n  }\n\n}\n```\n\n### Example Usage\n\n```jsx\n<StatefulComponent /> // throws error, property \"value\" is missing\n<StatefulComponent value=\"foo\" /> // ok\n<StatefulComponent value=\"foo\" optionalValue={true} /> // throws error, value \"true\" is not assignable to type string\n```\n\n## Functional Components\n\nFunctional components are components do not use state and are simple javascript functions accepting props and returns a single JSX/VDOM element.\n\n```jsx\nimport { h } from 'preact';\n\nexport interface Props {\n  value: string,\n  optionalValue?: string\n}\n\nexport default function SomeFunctionalComponent({ value, optionalValue }: Props) {\n  return (\n    <div>\n      {value} {optionalValue}\n    </div>\n  );\n}\n```\n\n### Example Usage\n\n```jsx\n<SomeFunctionalComponent /> // throws error, property \"value\" is missing\n<SomeFunctionalComponent value=\"foo\" /> // ok\n<SomeFunctionalComponent value=\"foo\" optionalValue={true} /> // throws error, value \"true\" is not assignable to type string\n```\n\nYou can also use named variables with `FunctionalComponent<Props>`.\n\n```jsx\nimport { h, FunctionalComponent } from 'preact';\n\nexport interface Props {\n  value: string,\n  optionalValue?: string\n}\n\nexport const SomeFunctionalComponent: FunctionalComponent<Props> = ({ value, optionalValue }: Props) => {\n  return (\n    <div>\n      {value} {optionalValue}\n    </div>\n  );\n};\n```\n\n## Components with Children\n\nIt's likely at some point you will want to nest elements, and with Typescript you can validate that any children props are valid JSX elements.\n\n```jsx\nimport { h } from 'preact';\n\nexport interface Props {\n  children?: JSX.Element[]\n}\n\nexport function A() {\n  return <div></div>;\n}\n\nexport function B() {\n  return 'foo';\n}\n\nexport default function ComponentWithChildren({ children }: Props) {\n  return (\n    <div>\n      {children}\n    </div>\n  )\n}\n```\n\n### Example Usage\n\n```jsx\n<ComponentWithChildren /> // ok\n\n// ok\n<ComponentWithChildren>\n  <span></span>\n</ComponentWithChildren>\n\n// ok\n<ComponentWithChildren>\n  <A />\n</ComponentWithChildren>\n\n// throws error, not a valid JSX Element\n<ComponentWithChildren>\n  <B />\n</ComponentWithChildren>\n```\n\n## Higher Order Components (HOC)\n\nUsing Higher Order Components (HOC) allows for certain component logic to be reused and is a natural pattern for compositional components. An HOC is simply a function that takes a component and returns that component.\n\n```jsx\n// app/hoc.tsx\n\nimport { h, AnyComponent, Component } from 'preact';\n\nexport interface Props {\n  email: string\n}\n\nexport interface State {\n  firstName: string,\n  lastName: string\n}\n\nexport default function HOC<P extends Props>(SomeComponent: AnyComponent<any, any>) {\n  return class extends Component<P, State> {\n    componentDidMount() {\n      let { email } = this.props;\n      fetch(`/user/${email}`)\n        .then((response: any) => response.json())\n        .then(({ firstName, lastName }) => this.setState({ firstName, lastName }))\n    }\n\n    render(props, state) {\n      return <SomeComponent {...props} {...state} />;\n    }\n  }\n}\n```\n\nThen, you can wrap your components with your HOC simplifying view logic to potentially only *props*.\n\n\n```jsx\n// app/component.tsx\n\nimport { h } from 'preact';\nimport HOC from './hoc';\n\nexport interface Props {\n  firstName: string,\n  lastName: string,\n  email: string\n}\n\nfunction FunctionalUserComponent({ firstName, lastName, email }: Props) {\n  return <div>{firstName} {lastName}: { email }</div>\n}\n\nexport default HOC<{ email: string }>(FunctionalUserComponent);\n```\n\n### Example Usage\n\n```jsx\n// import FunctionalUserComponent from './app/component'\n\n<FunctionalUserComponent /> // throws error, property \"email\" is missing\n<FunctionalUserComponent email=\"foo@bar.com\" /> // ok, first and last names are resolved by the HOC\n```\n\n## Extending HTML Attributes\n\nIf you have a component that passes down unknown HTML attributes using, you can extend `JSX.HtmlAttributes` to allow any valid HTML attribute for your component.\n\n```jsx\nimport { h, Component } from 'preact';\n\nexport interface Props {\n  value?: string\n}\n\nexport default class ComponentWithHtmlAttributes extends Component<JSX.HtmlAttributes & Props, any> {\n  render({ value, ...otherProps }: Props, {}: any) {\n    return (\n      <div {...otherProps}>{value}</div>\n    );\n  }\n}\n```\n\n### Example Usage\n\n```jsx\n<ComponentWithHtmlAttributes /> // ok\n<ComponentWithHtmlAttributes class=\"foo\" /> // ok, valid html attribute\n<ComponentWithHtmlAttributes foo=\"bar\" /> // throws error, invalid html attribute\n```\n\n## Rendering\n\nRendering components requires an `Element`. The second argument will append your component to your node:\n\n```jsx\nimport { h, render } from 'preact';\nimport MyComponent from './MyComponent';\n\nrender(<MyComponent />, document.body as Element);\n```\n\nAdditionally, you can choose to replace a specific node by specifying a third argument:\n\n```jsx\nimport { h, render } from 'preact';\nimport MyComponent from './MyComponent';\n\nconst node = document.getElementById('root') as Element;\nrender(<MyComponent />, node, node.firstElementChild as Element);\n```\n\n## Custom Elements / Web Components\n\nWith vanilla JSX in preact, you can create any element with whatever name you want and it'll get transpiled to `h('my-element-name', ...)`. However Typescript is more opinionated and will complain if an imported component or HTML element does not exist with that name. Normally, this is what you would want with Preact components but custom elements may or may not be imported into your JSX files.\n\nFor Typescript there is a special interface [`JSX.IntrinsicElements`](https://www.typescriptlang.org/docs/handbook/jsx.html#intrinsic-elements) available where you can define additional elements for Typescript to include. As a bonus, you can define any custom attributes as properties gaining additional type safety for custom elements in JSX!\n\n> typings.d.ts\n\n```jsx\nexport interface MyCustomElementProps {\n  value: string,\n  optionalValue?: string\n}\n\ndeclare module JSX {\n  interface IntrinsicElements {\n    \"my-custom-element\": MyCustomElementProps\n  }\n}\n```\n\n### Example Usage\n\n\n```jsx\n<my-custom-element /> // throws error, property \"value\" is missing\n<my-custom-element value=\"foo\" /> // ok\n<my-custom-element value=\"foo\" optionalValue={true} /> // throws error, value \"true\" is not assignable to type string\n```\n"
  }
]