From 917b97cadd09f4233a1a0ab4b5d11fb9ec38d6b6 Mon Sep 17 00:00:00 2001 From: Alex Macleod Date: Mon, 21 May 2018 22:42:52 +0100 Subject: [PATCH] Add typescript child type checking Closes #1086 It fixes the original issue from #1008, it will now type check correctly It also allows type inference (and checking) of function bodies, a basic example is given in the docs that infers the type of `num` but anything like developit/preact-router#269 can benefit from this --- src/preact.d.ts | 12 ++++++++---- test/ts/VNode-test.tsx | 6 ++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/preact.d.ts b/src/preact.d.ts index 9c2f0c6391b..984d18b5a8f 100644 --- a/src/preact.d.ts +++ b/src/preact.d.ts @@ -4,8 +4,8 @@ export as namespace preact; declare namespace preact { type Key = string | number; type Ref = (instance: T) => void; - type ComponentChild = JSX.Element | string | number | null; - type ComponentChildren = ComponentChild[]; + type ComponentChild = VNode | string | number | null; + type ComponentChildren = ComponentChild[] | ComponentChild | {} | string | number | null; /** * @deprecated @@ -104,12 +104,12 @@ declare namespace preact { function h

( node: ComponentFactory

, params: Attributes & P | null, - ...children: (ComponentChild | ComponentChildren)[] + ...children: ComponentChildren[] ): VNode; function h( node: string, params: JSX.HTMLAttributes & JSX.SVGAttributes & Record | null, - ...children: (ComponentChild | ComponentChildren)[] + ...children: ComponentChildren[] ): VNode; function render(node: ComponentChild, parent: Element | Document, mergeWith?: Element): Element; @@ -136,6 +136,10 @@ declare global { props: any; } + interface ElementChildrenAttribute { + children: any; + } + interface SVGAttributes extends HTMLAttributes { accentHeight?: number | string; accumulate?: "none" | "sum"; diff --git a/test/ts/VNode-test.tsx b/test/ts/VNode-test.tsx index 3e6258eebf8..3c950e510ea 100644 --- a/test/ts/VNode-test.tsx +++ b/test/ts/VNode-test.tsx @@ -57,3 +57,9 @@ describe("VNode", () => { expect(comp.children[1]).to.be.a("string"); }); }); + +class TypedChildren extends Component<{children: (num: number) => string}> { + render() { return null } +} + +const typedChild = {num => num.toFixed(2)}