Skip to content

Commit

Permalink
Add typescript child type checking
Browse files Browse the repository at this point in the history
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 preactjs/preact-router#269 can benefit from this
  • Loading branch information
Alexendoo committed May 21, 2018
1 parent 2d0e76e commit 917b97c
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/preact.d.ts
Expand Up @@ -4,8 +4,8 @@ export as namespace preact;
declare namespace preact {
type Key = string | number;
type Ref<T> = (instance: T) => void;
type ComponentChild = JSX.Element | string | number | null;
type ComponentChildren = ComponentChild[];
type ComponentChild = VNode<any> | string | number | null;
type ComponentChildren = ComponentChild[] | ComponentChild | {} | string | number | null;

/**
* @deprecated
Expand Down Expand Up @@ -104,12 +104,12 @@ declare namespace preact {
function h<P>(
node: ComponentFactory<P>,
params: Attributes & P | null,
...children: (ComponentChild | ComponentChildren)[]
...children: ComponentChildren[]
): VNode<any>;
function h(
node: string,
params: JSX.HTMLAttributes & JSX.SVGAttributes & Record<string, any> | null,
...children: (ComponentChild | ComponentChildren)[]
...children: ComponentChildren[]
): VNode<any>;

function render(node: ComponentChild, parent: Element | Document, mergeWith?: Element): Element;
Expand All @@ -136,6 +136,10 @@ declare global {
props: any;
}

interface ElementChildrenAttribute {
children: any;
}

interface SVGAttributes extends HTMLAttributes {
accentHeight?: number | string;
accumulate?: "none" | "sum";
Expand Down
6 changes: 6 additions & 0 deletions test/ts/VNode-test.tsx
Expand Up @@ -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 = <TypedChildren>{num => num.toFixed(2)}</TypedChildren>

0 comments on commit 917b97c

Please sign in to comment.