diff --git a/types/use-subscription/index.d.ts b/types/use-subscription/index.d.ts new file mode 100644 index 0000000000..1001d42790 --- /dev/null +++ b/types/use-subscription/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for use-subscription 1.0 +// Project: https://github.com/facebook/react/ +// Definitions by: Sebastian Silbermann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export type Unsubscribe = () => void; + +export interface Subscription { + /** + * (Synchronously) returns the current value of our subscription. + */ + getCurrentValue: () => T; + /** + * This function is passed an event handler to attach to the subscription. + * It must return an unsubscribe function that removes the handler. + */ + subscribe: (callback: () => void) => Unsubscribe; +} + +export function useSubscription(subscription: Subscription): T; diff --git a/types/use-subscription/tsconfig.json b/types/use-subscription/tsconfig.json new file mode 100644 index 0000000000..8ea91df0fe --- /dev/null +++ b/types/use-subscription/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "use-subscription-tests.ts" + ] +} diff --git a/types/use-subscription/tslint.json b/types/use-subscription/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/use-subscription/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/use-subscription/use-subscription-tests.ts b/types/use-subscription/use-subscription-tests.ts new file mode 100644 index 0000000000..c8615d9c96 --- /dev/null +++ b/types/use-subscription/use-subscription-tests.ts @@ -0,0 +1,22 @@ +import { useMemo } from 'react'; +import { useSubscription, Subscription } from 'use-subscription'; + +// https://github.com/facebook/react/tree/d96f478f8a79da3125f6842c16efbc2ae8bcd3bf/packages/use-subscription#subscribing-to-event-dispatchers +function EventDispatcherExample({ input }: { input: HTMLInputElement }) { + const subscription = useMemo( + (): Subscription => ({ + getCurrentValue: () => input.value, + subscribe: callback => { + input.addEventListener('change', callback); + return () => input.removeEventListener('change', callback); + }, + }), + + [input], + ); + + // $ExpectType string + const value = useSubscription(subscription); + + // Your rendered output goes here ... +}