[use-subscription] Add types (#38324)

This commit is contained in:
Sebastian Silbermann 2019-09-24 23:39:27 +02:00 committed by Ben Lichtman
parent adc769c638
commit 717634b5f4
4 changed files with 68 additions and 0 deletions

21
types/use-subscription/index.d.ts vendored Normal file
View File

@ -0,0 +1,21 @@
// Type definitions for use-subscription 1.0
// Project: https://github.com/facebook/react/
// Definitions by: Sebastian Silbermann <https://github.com/eps1lon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
export type Unsubscribe = () => void;
export interface Subscription<T> {
/**
* (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<T>(subscription: Subscription<T>): T;

View File

@ -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"
]
}

View File

@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }

View File

@ -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<string> => ({
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 ...
}