diff --git a/package.json b/package.json index 7fc0358f27..1a5124c035 100644 --- a/package.json +++ b/package.json @@ -21,7 +21,7 @@ "lint": "dtslint types" }, "devDependencies": { - "dtslint": "github:Microsoft/dtslint#production", + "dtslint": "latest", "types-publisher": "github:Microsoft/types-publisher#production" }, "dependencies": {} diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index 92c090d179..fdd0f395fe 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -97,6 +97,7 @@ let _algoliaIndexSettings: IndexSettings = { minProximity: 0, placeholders: { '': [''] }, camelCaseAttributes: [''], + sortFacetValuesBy: 'count', }; let _algoliaQueryParameters: QueryParameters = { @@ -150,6 +151,7 @@ let _algoliaQueryParameters: QueryParameters = { synonyms: true, replaceSynonymsInHighlight: false, minProximity: 0, + sortFacetValuesBy: 'alpha', }; let client: Client = algoliasearch('', ''); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index 5478fedbac..f25d901f73 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1451,6 +1451,11 @@ declare namespace algoliasearch { nbShards?: number; userData?: string | object; + + /** + * https://www.algolia.com/doc/api-reference/api-parameters/sortFacetValuesBy/ + */ + sortFacetValuesBy?: 'count' | 'alpha'; } namespace SearchForFacetValues { @@ -1776,6 +1781,8 @@ declare namespace algoliasearch { https://www.algolia.com/doc/api-reference/api-parameters/camelCaseAttributes/ */ camelCaseAttributes?: string[]; + + sortFacetValuesBy?: 'count' | 'alpha'; } interface Response { diff --git a/types/algoliasearch/lite/index.d.ts b/types/algoliasearch/lite/index.d.ts index ce58d6a428..5c9457df22 100644 --- a/types/algoliasearch/lite/index.d.ts +++ b/types/algoliasearch/lite/index.d.ts @@ -531,6 +531,11 @@ declare namespace algoliasearch { nbShards?: number; userData?: string | object; + + /** + * https://www.algolia.com/doc/api-reference/api-parameters/sortFacetValuesBy/ + */ + sortFacetValuesBy?: 'count' | 'alpha'; } namespace SearchForFacetValues { diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index acc7341a84..6b012d5677 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -346,7 +346,7 @@ declare module 'angular' { interface IMenuService { close(): void; hide(response?: any, options?: any): IPromise; - open(event?: MouseEvent): void; + open(event?: MouseEvent | JQueryEventObject): void; } interface IColorPalette { diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index 46c146272e..13ae21f5a4 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -143,6 +143,8 @@ pdfQueue .on('drained', () => undefined) .on('removed', (job: Queue.Job) => undefined); +pdfQueue.setMaxListeners(42); + // test different process methods const profileQueue = new Queue('profile'); diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index aab2385ea4..cd2d1a9047 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -17,6 +17,7 @@ // TypeScript Version: 2.8 import * as Redis from "ioredis"; +import { EventEmitter } from "events"; /** * This is the Queue constructor. @@ -384,7 +385,7 @@ declare namespace Bull { next: number; } - interface Queue { + interface Queue extends EventEmitter { /** * The name of the queue */ diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts index e86d2a94af..af85cde068 100644 --- a/types/catbox/catbox-tests.ts +++ b/types/catbox/catbox-tests.ts @@ -18,6 +18,9 @@ const Memory: EnginePrototypeOrObject = { const client = new Client(Memory, { partition: 'cache' }); +client.start().then(() => {}); +client.stop().then(() => {}); + const cache = new Policy({ expiresIn: 5000, }, client, 'cache'); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index bd41889e07..e90768be20 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -23,7 +23,7 @@ export class Client implements ClientApi { /** start() - creates a connection to the cache server. Must be called before any other method is available. */ start(): Promise; /** stop() - terminates the connection to the cache server. */ - stop(): void; + stop(): Promise; /** * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 058bfd78ea..211b6a59d8 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -5246,7 +5246,7 @@ declare namespace chrome.runtime { export interface PortMessageEvent extends chrome.events.Event<(message: any, port: Port) => void> { } - export interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response: any) => void) => void> { } + export interface ExtensionMessageEvent extends chrome.events.Event<(message: any, sender: MessageSender, sendResponse: (response?: any) => void) => void> { } export interface ExtensionConnectEvent extends chrome.events.Event<(port: Port) => void> { } diff --git a/types/co/co-tests.ts b/types/co/co-tests.ts new file mode 100644 index 0000000000..159a2e90fb --- /dev/null +++ b/types/co/co-tests.ts @@ -0,0 +1,30 @@ +import co = require('co'); + +function* gen(num: number, str: string, arr: number[], obj: object, fun: () => void) { + return num; +} + +co(gen, 42, 'forty-two', [42], { value: 42 }, () => {}) + .then((num: number) => {}, (err: Error) => {}) + .catch((err: Error) => {}); + +co.default(gen, 42, 'forty-two', [42], { value: 42 }, () => {}) + .then((num: number) => {}, (err: Error) => {}) + .catch((err: Error) => {}); + +co.co(gen, 42, 'forty-two', [42], { value: 42 }, () => {}) + .then((num: number) => {}, (err: Error) => {}) + .catch((err: Error) => {}); + +co.wrap(gen)(42, 'forty-two', [42], { value: 42 }, () => {}) + .then((num: number) => {}, (err: Error) => {}) + .catch((err: Error) => {}); + +// $ExpectError +co(gen, 42, 'forty-two', [42], { value: 42 }, () => {}).then((str: string) => {}); + +// $ExpectError +co.wrap(gen)(); + +// $ExpectError +co.wrap(gen)('forty-two'); diff --git a/types/co/index.d.ts b/types/co/index.d.ts new file mode 100644 index 0000000000..958c222a14 --- /dev/null +++ b/types/co/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for co 4.6 +// Project: https://github.com/tj/co#readme +// Definitions by: Doniyor Aliyev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.1 + +type ExtractType = T extends IterableIterator ? R : never; + +interface Co { + Generator>(fn: F, ...args: Parameters): Promise>>; + default: Co; + co: Co; + wrap: Generator>(fn: F) => (...args: Parameters) => Promise>>; +} + +declare const co: Co; + +export = co; diff --git a/types/co/tsconfig.json b/types/co/tsconfig.json new file mode 100644 index 0000000000..bc5a88eb32 --- /dev/null +++ b/types/co/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "co-tests.ts" + ] +} diff --git a/types/co/tslint.json b/types/co/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/co/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index df6870c70a..b4ca7de92f 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.2 +// Type definitions for Cytoscape.js 3.3 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -464,6 +464,27 @@ declare namespace cytoscape { */ endBatch(): void; + /** + * Attaches the instance to the specified container for visualisation. + * http://js.cytoscape.org/#cy.mount + * + * If the core instance is headless prior to calling cy.mount(), then + * the instance will no longer be headless and the visualisation will + * be shown in the specified container. If the core instance is + * non-headless prior to calling cy.mount(), then the visualisation + * is swapped from the prior container to the specified container. + */ + mount(element: Element): void; + + /** + * Remove the instance from its current container. + * http://js.cytoscape.org/#cy.unmount + * + * This function sets the instance to be headless after unmounting from + * the current container. + */ + unmount(): void; + /** * A convenience function to explicitly destroy the Core. * http://js.cytoscape.org/#cy.destroy diff --git a/types/debug/index.d.ts b/types/debug/index.d.ts index 954ca3a35a..715e7c145e 100644 --- a/types/debug/index.d.ts +++ b/types/debug/index.d.ts @@ -38,7 +38,7 @@ declare namespace debug { (formatter: any, ...args: any[]): void; enabled: boolean; - log: (v: any) => string; + log: (...args: any[]) => any; namespace: string; extend: (namespace: string, delimiter?: string) => Debugger; } diff --git a/types/elliptic/index.d.ts b/types/elliptic/index.d.ts index 722568a6f6..7b1e885d6f 100644 --- a/types/elliptic/index.d.ts +++ b/types/elliptic/index.d.ts @@ -187,7 +187,7 @@ export class ec { export namespace ec { interface GenKeyPairOptions { - pers: any; + pers?: any; entropy: any; persEnc?: string; entropyEnc?: string; diff --git a/types/favicons/index.d.ts b/types/favicons/index.d.ts index 782ad0cb7c..730841dff9 100644 --- a/types/favicons/index.d.ts +++ b/types/favicons/index.d.ts @@ -9,7 +9,7 @@ import { Duplex } from "stream"; declare namespace favicons { - interface Configuration { + interface Configuration { /** Path for overriding default icons path @default "/" */ path: string; /** Your application's name @default null */ @@ -38,6 +38,8 @@ declare namespace favicons { version: string; /** Print logs to console? @default false */ logging: boolean; + /** Use nearest neighbor resampling to preserve hard edges on pixel art @default false */ + pixel_art: boolean; /** * Platform Options: * - offset - offset in percentage @@ -66,18 +68,18 @@ declare namespace favicons { }>; } - interface FavIconResponse { + interface FavIconResponse { images: Array<{ name: string; contents: Buffer }>; files: Array<{ name: string; contents: Buffer }>; html: string[]; } - type Callback = (error: Error | null, response: FavIconResponse) => void; + type Callback = (error: Error | null, response: FavIconResponse) => void; /** You can programmatically access Favicons configuration (icon filenames, HTML, manifest files, etc) with this export */ - const config: Configuration; + const config: Configuration; - function stream(configuration?: Configuration): Duplex; + function stream(configuration?: Configuration): Duplex; } /** * Generate favicons diff --git a/types/firefox-webext-browser/index.d.ts b/types/firefox-webext-browser/index.d.ts index 1dfe1eb809..c0a8896e56 100644 --- a/types/firefox-webext-browser/index.d.ts +++ b/types/firefox-webext-browser/index.d.ts @@ -3188,7 +3188,7 @@ declare namespace browser.storage { * @param changes Object mapping each key that changed to its corresponding `storage.StorageChange` for that item. * @param areaName The name of the storage area (`"sync"`, `"local"` or `"managed"`) the changes are for. */ - const onChanged: WebExtEvent<(changes: StorageChange, areaName: string) => void>; + const onChanged: WebExtEvent<(changes: {[key: string]: StorageChange}, areaName: string) => void>; } /** diff --git a/types/iobroker/index.d.ts b/types/iobroker/index.d.ts index 71fa1b4d78..e9b2f64e67 100644 --- a/types/iobroker/index.d.ts +++ b/types/iobroker/index.d.ts @@ -1627,11 +1627,11 @@ declare global { removeAllListeners(event?: "ready" | "unload" | "stateChange" | "objectChange" | "message"): this; } // end interface Adapter - type ReadyHandler = () => void; - type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void; - type StateChangeHandler = (id: string, obj: State | null | undefined) => void; - type MessageHandler = (obj: Message) => void; - type UnloadHandler = (callback: EmptyCallback) => void; + type ReadyHandler = () => void | Promise; + type ObjectChangeHandler = (id: string, obj: ioBroker.Object | null | undefined) => void | Promise; + type StateChangeHandler = (id: string, obj: State | null | undefined) => void | Promise; + type MessageHandler = (obj: Message) => void | Promise; + type UnloadHandler = (callback: EmptyCallback) => void | Promise; type EmptyCallback = () => void; type ErrorCallback = (err?: string) => void; diff --git a/types/iobroker/iobroker-tests.ts b/types/iobroker/iobroker-tests.ts index 0302a5041a..0b707098fa 100644 --- a/types/iobroker/iobroker-tests.ts +++ b/types/iobroker/iobroker-tests.ts @@ -20,6 +20,16 @@ adapter ; adapter.removeAllListeners(); +// Test adapter constructor options +let adapterOptions: ioBroker.AdapterOptions = { + name: "foo", + ready: readyHandler, + stateChange: stateChangeHandler, + objectChange: objectChangeHandler, + message: messageHandler, + unload: unloadHandler, +}; + function readyHandler() { } function stateChangeHandler(id: string, state: ioBroker.State | null | undefined) { diff --git a/types/ioredis/index.d.ts b/types/ioredis/index.d.ts index d5f829c8fe..743c3c061a 100644 --- a/types/ioredis/index.d.ts +++ b/types/ioredis/index.d.ts @@ -489,6 +489,8 @@ declare namespace IORedis { xack(key: KeyType, group: string, ...ids: string[]): any; xadd(key: KeyType, id: string, ...args: string[]): any; + xadd(key: KeyType, maxLenOption: 'MAXLEN' | 'maxlen', count: number, ...args: string[]): any; + xadd(key: KeyType, maxLenOption: 'MAXLEN' | 'maxlen', approximate: '~', count: number, ...args: string[]): any; xclaim(key: KeyType, group: string, consumer: string, minIdleTime: number, ...args: any[]): any; diff --git a/types/ioredis/ioredis-tests.ts b/types/ioredis/ioredis-tests.ts index 9950a8543f..89e4120f0e 100644 --- a/types/ioredis/ioredis-tests.ts +++ b/types/ioredis/ioredis-tests.ts @@ -177,6 +177,8 @@ new Redis.Cluster([{ redis.xack('streamName', 'groupName', 'id'); redis.xadd('streamName', '*', 'field', 'name'); +redis.xadd('streamName', 'MAXLEN', 100, '*', 'field', 'name'); +redis.xadd('streamName', 'MAXLEN', '~', 100, '*', 'field', 'name'); redis.xclaim('streamName', 'groupName', 'consumerName', 3600000, 'id'); redis.xdel('streamName', 'id'); redis.xgroup('CREATE', 'streamName', 'groupName', '$'); diff --git a/types/jasmine-data_driven_tests/index.d.ts b/types/jasmine-data_driven_tests/index.d.ts index 8c719de652..553987ef60 100644 --- a/types/jasmine-data_driven_tests/index.d.ts +++ b/types/jasmine-data_driven_tests/index.d.ts @@ -34,6 +34,6 @@ interface JasmineDataDrivenTest { assertion: (arg0: T, arg1: U, done: () => void) => void): void; ( description: string, - dataset: T[], + dataset: T[] | Array<[T]>, assertion: (value: T, done: () => void) => void): void; } diff --git a/types/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts b/types/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts index 6689159b58..0523a28af0 100644 --- a/types/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts +++ b/types/jasmine-data_driven_tests/jasmine-data_driven_tests-tests.ts @@ -37,6 +37,13 @@ xall("A data driven test can be pending", } ); +all("A data set must consist of array-wrapped arrays, if test expects single array input", + [[[1, 2]], [[3, 4]], [[5, 6]]], + (numberArray: number[]) => { + expect(numberArray.length).toBe(2); + } +); + describe("A suite", () => { let a: number; diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 29b3210cc2..f0382d2cb5 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -978,20 +978,29 @@ declare namespace jest { } /** - * Represents the result of a single call to a mock function. + * Represents the result of a single call to a mock function with a return value. */ - interface MockResult { - /** - * True if the function threw. - * False if the function returned. - */ - isThrow: boolean; - /** - * The value that was either thrown or returned by the function. - */ + interface MockResultReturn { + type: 'return'; + value: T; + } + /** + * Represents the result of a single incomplete call to a mock function. + */ + interface MockResultIncomplete { + type: 'incomplete'; + value: undefined; + } + /** + * Represents the result of a single call to a mock function with a thrown error. + */ + interface MockResultThrow { + type: 'throw'; value: any; } + type MockResult = MockResultReturn | MockResultThrow | MockResultIncomplete; + interface MockContext { calls: Y[]; instances: T[]; @@ -999,7 +1008,7 @@ declare namespace jest { /** * List of results of calls to the mock function. */ - results: MockResult[]; + results: Array>; } } diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index 11b3752a0a..69e68ab6f7 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -316,7 +316,7 @@ interface TestApi { test(x: number): string; } // $ExpectType Mock -const mock12 = jest.fn, ArgsType>(); +const mock12 = jest.fn, jest.ArgsType>(); // $ExpectType number mock1('test'); @@ -485,6 +485,19 @@ mocked.test4.mockRejectedValue(new Error()); // $ExpectError mocked.test4.mockRejectedValueOnce(new Error()); +const mockResult = jest.fn(() => 1).mock.results[0]; +switch (mockResult.type) { + case 'return': + mockResult.value; // $ExpectType number + break; + case 'incomplete': + mockResult.value; // $ExpectType undefined + break; + case 'throw': + mockResult.value; // $ExpectType any + break; +} + /* Snapshot serialization */ const snapshotSerializerPlugin: jest.SnapshotSerializerPlugin = { diff --git a/types/jsoneditor/index.d.ts b/types/jsoneditor/index.d.ts index f095cb8434..3c74a3d789 100644 --- a/types/jsoneditor/index.d.ts +++ b/types/jsoneditor/index.d.ts @@ -1,54 +1,199 @@ -// Type definitions for jsoneditor v5.19.0 +// Type definitions for jsoneditor v5.28.2 // Project: https://github.com/josdejong/jsoneditor // Definitions by: Alejandro Sánchez // Errietta Kostala +// Adam Vigneaux // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// +import { Ajv } from "ajv"; + declare module 'jsoneditor' { - export interface JSONEditorNode { + type JSONPath = (string|number)[]; + + export interface Node { field: string; - value: string; - path: Array; + value?: string; + path: JSONPath; } export type JSONEditorMode = 'tree' | 'view' | 'form' | 'code' | 'text'; + export interface NodeName { + path: string; + type: 'object'|'array'; + size: number; + } + + export interface ValidationError { + path: JSONPath; + message: string; + } + + export interface Template { + text: string; + title: string; + className?: string; + field: string; + value: any; + } + + export type AutoCompleteCompletion = null|string[]|{startFrom: number, options: string[]}; + + export type AutoCompleteOptionsGetter = ( + text: string, path: JSONPath, input: string, editor: JSONEditor, + ) => AutoCompleteCompletion|Promise; + + export interface AutoCompleteOptions { + /** + * @default [39, 35, 9] + */ + confirmKeys?: number[]; + caseSensitive?: boolean; + getOptions?: AutoCompleteOptionsGetter; + } + + export interface SelectionPosition { + row: number; + column: number; + } + + export interface SerializableNode { + value: any; + path: JSONPath; + } + + // Based on the API of https://github.com/Sphinxxxx/vanilla-picker + export interface Color { + rgba: Array; + hsla: Array; + rgbString: string; + rgbaString: string; + hslString: string; + hslaString: string; + hex: string; + } + export interface JSONEditorOptions { ace?: AceAjax.Ace; - ajv?: any; // Any for now, since ajv typings aren't A-Ok + ajv?: Ajv; onChange?: () => void; - onEditable?: (node: JSONEditorNode) => boolean | {field: boolean, value: boolean}; + onChangeJSON?: (json: any) => void; + onChangeText?: (jsonString: string) => void; + onEditable?: (node: Node) => boolean|{field: boolean, value: boolean}; onError?: (error: Error) => void; onModeChange?: (newMode: JSONEditorMode, oldMode: JSONEditorMode) => void; + onNodeName?: (nodeName: NodeName) => string|undefined; + onValidate?: (json: any) => ValidationError[]|Promise; + /** + * @default false + */ escapeUnicode?: boolean; + /** + * @default false + */ sortObjectKeys?: boolean; + /** + * @default true + */ history?: boolean; + /** + * @default 'tree' + */ mode?: JSONEditorMode; - modes?: Array; + modes?: JSONEditorMode[]; + /** + * @default undefined + */ name?: string; - schema?: Object; - schemaRefs?: Object; + schema?: object; + schemaRefs?: object; + /** + * @default true + */ search?: boolean; + /** + * @default 2 + */ indentation?: number; theme?: string; + templates?: Template[]; + autocomplete?: AutoCompleteOptions; + /** + * @default true + */ + mainMenuBar?: boolean; + /** + * @default true + */ + navigationBar?: boolean; + /** + * @default true + */ + statusBar?: boolean; + onTextSelectionChange?: (start: SelectionPosition, end: SelectionPosition, text: string) => void; + onSelectionChange?: (start: SerializableNode, end: SerializableNode) => void; + onEvent?: (node: Node, event: string) => void; + /** + * @default true + */ + colorPicker?: boolean; + onColorPicker?: (parent: HTMLElement, color: string, onChange: (color: Color) => void) => void; + /** + * @default true + */ + timestampTag?: boolean; + language?: string; + languages?: { + [lang: string]: { + [key: string]: string; + }; + }; + modalAnchor?: HTMLElement; + /** + * @default true + */ + enableSort?: boolean; + /** + * @default true + */ + enableTransform?: boolean; + /** + * @default 100 + */ + maxVisibleChilds?: number; + } export default class JSONEditor { - constructor(container: HTMLElement, options?: JSONEditorOptions, json?: Object); + constructor(container: HTMLElement, options?: JSONEditorOptions, json?: any); collapseAll(): void; destroy(): void; expandAll(): void; focus(): void; - set(json: Object): void; - setMode(mode: JSONEditorMode): void; - setName(name?: string): void; - setSchema(schema: Object): void; - setText(jsonString: string): void; get(): any; getMode(): JSONEditorMode; - getName(): string; + getName(): string|undefined; + getNodesByRange(start: {path: JSONPath}, end: {path: JSONPath}): Array; + getSelection(): {start: SerializableNode, end: SerializableNode}; getText(): string; + getTextSelection(): {start: SelectionPosition, end: SelectionPosition, text: string}; + refresh(): void; + set(json: any): void; + setMode(mode: JSONEditorMode): void; + setName(name?: string): void; + setSchema(schema: object, schemaRefs?: object): void; + setSelection(start: {path: JSONPath}, end: {path: JSONPath}): void; + setText(jsonString: string): void; + setTextSelection(start: SelectionPosition, end: SelectionPosition): void; + update(json: any): void; + updateText(jsonString: string): void; + + static VALID_OPTIONS: Array; + static ace: AceAjax.Ace; + static Ajv: Ajv; + static VanillaPicker: any; } } diff --git a/types/jsoneditor/jsoneditor-tests.ts b/types/jsoneditor/jsoneditor-tests.ts index d905e6ba76..b584a14416 100644 --- a/types/jsoneditor/jsoneditor-tests.ts +++ b/types/jsoneditor/jsoneditor-tests.ts @@ -1,11 +1,13 @@ -import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions } from 'jsoneditor'; +import * as Ajv from 'ajv'; +import JSONEditor, {JSONEditorMode, Node, JSONEditorOptions } from 'jsoneditor'; let options: JSONEditorOptions; +options = {}; options = { ace: ace, - //ajv: Ajv({allErrors: true, verbose: true}) + ajv: new Ajv({allErrors: true, verbose: true}), onChange() {}, - onEditable(node: JSONEditorNode) { + onEditable(node: Node) { return true; }, onError(error: Error) {}, @@ -23,7 +25,7 @@ options = { theme: 'default' }; options = { - onEditable(node: JSONEditorNode) { + onEditable(node: Node) { return {field: true, value: false}; } }; diff --git a/types/jsoneditor/package.json b/types/jsoneditor/package.json new file mode 100644 index 0000000000..b47ef67b0a --- /dev/null +++ b/types/jsoneditor/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "ajv": "*" + } +} diff --git a/types/klaw/index.d.ts b/types/klaw/index.d.ts index 7b4e586842..32810990d5 100644 --- a/types/klaw/index.d.ts +++ b/types/klaw/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for klaw v2.1.1 +// Type definitions for klaw v3.0.0 // Project: https://github.com/jprichardson/node-klaw // Definitions by: Matthew McEachen +// Pascal Sthamer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -26,6 +27,7 @@ declare module "klaw" { fs?: any // fs or mock-fs filter?: (path: string) => boolean depthLimit?: number + preserveSymlinks?: boolean } type Event = "close" | "data" | "end" | "readable" | "error" diff --git a/types/klaw/klaw-tests.ts b/types/klaw/klaw-tests.ts index 69406f73e8..baecd656f3 100644 --- a/types/klaw/klaw-tests.ts +++ b/types/klaw/klaw-tests.ts @@ -5,7 +5,7 @@ const path = require('path'); let items: klaw.Item[] = [] // files, directories, symlinks, etc -klaw('/some/dir') +klaw('/some/dir', { preserveSymlinks: false }) .on('data', function(item: klaw.Item) { items.push(item) }) diff --git a/types/luxon/index.d.ts b/types/luxon/index.d.ts index eebf89497d..44165c06c3 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -426,7 +426,7 @@ export class Interval { engulfs(other: Interval): boolean; equals(other: Interval): boolean; hasSame(unit: DurationUnit): boolean; - intersection(other: Interval): Interval; + intersection(other: Interval): Interval | null; isAfter(dateTime: DateTime): boolean; isBefore(dateTime: DateTime): boolean; isEmpty(): boolean; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index 59566c35c3..ecf49e2081 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -140,6 +140,7 @@ i.length('years'); // $ExpectType number i.contains(DateTime.local(2019)); // $ExpectType boolean i.set({end: DateTime.local(2020)}); // $ExpectType Interval i.mapEndpoints((d) => d); // $ExpectType Interval +i.intersection(i); // $ExpectType Interval | null i.toISO(); // $ExpectType string i.toString(); // $ExpectType string diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 267163ac80..2a01b58a95 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -337,7 +337,7 @@ declare module "mongoose" { /** Use ssl connection (needs to have a mongod server with ssl support) (default: true) */ ssl?: boolean; /** Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) */ - sslValidate?: object; + sslValidate?: boolean; /** Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. */ poolSize?: number; /** Reconnect on error (default: true) */ diff --git a/types/node-sass-middleware/index.d.ts b/types/node-sass-middleware/index.d.ts index badbd843d1..53cde2a10a 100644 --- a/types/node-sass-middleware/index.d.ts +++ b/types/node-sass-middleware/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sass/node-sass-middleware // Definitions by: Pascal Garber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.7 diff --git a/types/node-sass/index.d.ts b/types/node-sass/index.d.ts index b208b57f19..f5445689b4 100644 --- a/types/node-sass/index.d.ts +++ b/types/node-sass/index.d.ts @@ -1,56 +1,410 @@ -// Type definitions for Node Sass v3.10.1 +// Type definitions for node-sass 4.11 // Project: https://github.com/sass/node-sass -// Definitions by: Asana +// Definitions by: Asana , Chris Eppstein // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 /// -type ImporterReturnType = { file: string } | { contents: string } | Error | null; +export type ImporterReturnType = { file: string } | { file?: string; contents: string } | Error | null | types.Null | types.Error; -interface Importer { - (url: string, prev: string, done: (data: ImporterReturnType) => void): ImporterReturnType | void; +/** + * The context value is a value that is shared for the duration of a single render. + * The context object is the implicit `this` for importers and sass functions + * that are implemented in javascript. + * + * A render can be detected as asynchronous if the `callback` property is set on the context object. + */ +export interface Context { + options: Options; + callback: SassRenderCallback | undefined; + [data: string]: any; } -interface Options { - file?: string; - data?: string; - importer?: Importer | Importer[]; - functions?: { [key: string]: Function }; - includePaths?: string[]; - indentedSyntax?: boolean; - indentType?: string; - indentWidth?: number; - linefeed?: string; - omitSourceMapUrl?: boolean; - outFile?: string; - outputStyle?: "compact" | "compressed" | "expanded" | "nested"; - precision?: number; - sourceComments?: boolean; - sourceMap?: boolean | string; - sourceMapContents?: boolean; - sourceMapEmbed?: boolean; - sourceMapRoot?: string; +export interface AsyncContext extends Context { + callback: SassRenderCallback; } -interface SassError extends Error { - message: string; - line: number; - column: number; - status: number; - file: string; +export interface SyncContext extends Context { + callback: undefined; } -interface Result { - css: Buffer; - map: Buffer; - stats: { - entry: string; - start: number; - end: number; - duration: number; - includedFiles: string[]; - } +export type AsyncImporter = (this: AsyncContext, url: string, prev: string, done: (data: ImporterReturnType) => void) => void; +export type SyncImporter = (this: SyncContext, url: string, prev: string) => ImporterReturnType; +export type Importer = AsyncImporter | SyncImporter; + +// These function types enumerate up to 6 js arguments. More than that will be incorrectly marked by the compiler as an error. + +// ** Sync Sass functions receiving fixed # of arguments *** +export type SyncSassFn = (this: SyncContext, ...$args: types.Value[]) => types.ReturnValue; + +/* tslint:disable:max-line-length */ +// ** Sync Sass functions receiving variable # of arguments *** +export type SyncSassVarArgFn1 = (this: SyncContext, $arg1: types.Value[]) => types.ReturnValue; +export type SyncSassVarArgFn2 = (this: SyncContext, $arg1: types.Value, $arg2: types.Value[]) => types.ReturnValue; +export type SyncSassVarArgFn3 = (this: SyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value[]) => types.ReturnValue; +export type SyncSassVarArgFn4 = (this: SyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value[]) => types.ReturnValue; +export type SyncSassVarArgFn5 = (this: SyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value[]) => types.ReturnValue; +export type SyncSassVarArgFn6 = (this: SyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value, $arg6: types.Value[]) => types.ReturnValue; + +export type SassFunctionCallback = ($result: types.ReturnValue) => void; + +// ** Async Sass functions receiving fixed # of arguments *** +export type AsyncSassFn0 = (this: AsyncContext, cb: SassFunctionCallback) => void; +export type AsyncSassFn1 = (this: AsyncContext, $arg1: types.Value, cb: SassFunctionCallback) => void; +export type AsyncSassFn2 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, cb: SassFunctionCallback) => void; +export type AsyncSassFn3 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, cb: SassFunctionCallback) => void; +export type AsyncSassFn4 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, cb: SassFunctionCallback) => void; +export type AsyncSassFn5 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value, cb: SassFunctionCallback) => void; +export type AsyncSassFn6 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value, $arg6: types.Value, cb: SassFunctionCallback) => void; + +// *** Async Sass Functions receiving variable # of arguments *** +export type AsyncSassVarArgFn1 = (this: AsyncContext, $arg1: types.Value[], cb: SassFunctionCallback) => void; +export type AsyncSassVarArgFn2 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value[], cb: SassFunctionCallback) => void; +export type AsyncSassVarArgFn3 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value[], cb: SassFunctionCallback) => void; +export type AsyncSassVarArgFn4 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value[], cb: SassFunctionCallback) => void; +export type AsyncSassVarArgFn5 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value[], cb: SassFunctionCallback) => void; +export type AsyncSassVarArgFn6 = (this: AsyncContext, $arg1: types.Value, $arg2: types.Value, $arg3: types.Value, $arg4: types.Value, $arg5: types.Value, $arg6: types.Value[], cb: SassFunctionCallback) => void; +/* tslint:enable:max-line-length */ + +export type SyncSassFunction = SyncSassFn | SyncSassVarArgFn1 | SyncSassVarArgFn2 | SyncSassVarArgFn3 | SyncSassVarArgFn4 | SyncSassVarArgFn5 | SyncSassVarArgFn6; + +export type AsyncSassFunction = AsyncSassFn0 | AsyncSassFn1 | AsyncSassFn2 | AsyncSassFn3 | AsyncSassFn4 | AsyncSassFn5 | AsyncSassFn6 + | AsyncSassVarArgFn1 | AsyncSassVarArgFn2 | AsyncSassVarArgFn3 | AsyncSassVarArgFn4 | AsyncSassVarArgFn5 | AsyncSassVarArgFn6; + +export type SassFunction = SyncSassFunction | AsyncSassFunction; + +export type FunctionDeclarations = Record; + +export interface Options { + file?: string; + data?: string; + importer?: Importer | Importer[]; + functions?: FunctionDeclarations; + includePaths?: string[]; + indentedSyntax?: boolean; + indentType?: string; + indentWidth?: number; + linefeed?: string; + omitSourceMapUrl?: boolean; + outFile?: string; + outputStyle?: "compact" | "compressed" | "expanded" | "nested"; + precision?: number; + sourceComments?: boolean; + sourceMap?: boolean | string; + sourceMapContents?: boolean; + sourceMapEmbed?: boolean; + sourceMapRoot?: string; + [key: string]: any; } -export declare function render(options: Options, callback: (err: SassError, result: Result) => any): void; -export declare function renderSync(options: Options): Result; +export interface SyncOptions extends Options { + functions?: FunctionDeclarations; + importer?: SyncImporter | SyncImporter[]; +} + +/** + * The error object returned to javascript by sass's render methods. + * + * This is not the same thing as types.Error. + */ +export interface SassError extends Error { + message: string; + line: number; + column: number; + status: number; + file: string; +} + +/** + * The result of successfully compiling a Sass file. + */ +export interface Result { + css: Buffer; + map: Buffer; + stats: { + entry: string; + start: number; + end: number; + duration: number; + includedFiles: string[]; + }; +} +export type SassRenderCallback = (err: SassError, result: Result) => any; + +// Note, most node-sass constructors can be invoked as a function or with a new +// operator. The exception: the types Null and Boolean for which new is +// forbidden. +// +// Because of this, the new-able object notation is used here, a class does not +// work for these types. +export namespace types { + /* eslint-disable @typescript-eslint/ban-types */ + /* tslint:disable:ban-types */ + /** + * Values that are received from Sass as an argument to a javascript function. + */ + export type Value = Null | Number | String | Color | Boolean | List | Map; + + /** + * Values that are legal to return to Sass from a javascript function. + */ + export type ReturnValue = Value | Error; + + // *** Sass Null *** + + export interface Null { + /** + * This property doesn't exist, but its presence forces the typescript + * compiler to properly type check this type. Without it, it seems to + * allow things that aren't types.Null to match it in case statements and + * assignments. + */ + readonly ___NULL___: unique symbol; + } + + interface NullConstructor { + (): Null; + NULL: Null; + } + export const Null: NullConstructor; + + // *** Sass Number *** + + export interface Number { + getValue(): number; + setValue(n: number): void; + getUnit(): string; + setUnit(u: string): void; + } + interface NumberConstructor { + /** + * Constructs a new Sass number. Does not require use of the `new` keyword. + */ + new(value: number, unit?: string): Number; + /** + * Constructs a new Sass number. Can also be used with the `new` keyword. + */ + (value: number, unit?: string): Number; + } + + export const Number: NumberConstructor; + + // *** Sass String *** + + export interface String { + getValue(): string; + setValue(s: string): void; + } + + interface StringConstructor { + /** + * Constructs a new Sass string. Does not require use of the `new` keyword. + */ + new (value: string): String; + /** + * Constructs a new Sass string. Can also be used with the `new` keyword. + */ + (value: string): String; + } + + export const String: StringConstructor; + + // *** Sass Color *** + + export interface Color { + /** + * Get the red component of the color. + * @returns integer between 0 and 255 inclusive; + */ + getR(): number; + /** + * Set the red component of the color. + * @returns integer between 0 and 255 inclusive; + */ + setR(r: number): void; + /** + * Get the green component of the color. + * @returns integer between 0 and 255 inclusive; + */ + getG(): number; + /** + * Set the green component of the color. + * @param g integer between 0 and 255 inclusive; + */ + setG(g: number): void; + /** + * Get the blue component of the color. + * @returns integer between 0 and 255 inclusive; + */ + getB(): number; + /** + * Set the blue component of the color. + * @param b integer between 0 and 255 inclusive; + */ + setB(b: number): void; + /** + * Get the alpha transparency component of the color. + * @returns number between 0 and 1 inclusive; + */ + getA(): number; + /** + * Set the alpha component of the color. + * @param a number between 0 and 1 inclusive; + */ + setA(a: number): void; + } + + interface ColorConstructor { + /** + * Constructs a new Sass color given the RGBA component values. Do not invoke with the `new` keyword. + * + * @param r integer 0-255 inclusive + * @param g integer 0-255 inclusive + * @param b integer 0-255 inclusive + * @param [a] float 0 - 1 inclusive + * @returns a SassColor instance. + */ + new (r: number, g: number, b: number, a?: number): Color; + + /** + * Constructs a new Sass color given a 4 byte number. Do not invoke with the `new` keyword. + * + * If a single number is passed it is assumed to be a number that contains + * all the components which are extracted using bitmasks and bitshifting. + * + * @param hexN A number that is usually written in hexadecimal form. E.g. 0xff0088cc. + * @returns a Sass Color instance. + * @example + * // Comparison with byte array manipulation + * let a = new ArrayBuffer(4); + * let hexN = 0xCCFF0088; // 0xAARRGGBB + * let a32 = new Uint32Array(a); // Uint32Array [ 0 ] + * a32[0] = hexN; + * let a8 = new Uint8Array(a); // Uint8Array [ 136, 0, 255, 204 ] + * let componentBytes = [a8[2], a8[1], a8[0], a8[3] / 255] // [ 136, 0, 255, 0.8 ] + * let c = sass.types.Color(hexN); + * let components = [c.getR(), c.getG(), c.getR(), c.getA()] // [ 136, 0, 255, 0.8 ] + * assert.deepEqual(componentBytes, components); // does not raise. + */ + new (hexN: number): Color; + + /** + * Constructs a new Sass color given the RGBA component values. Do not invoke with the `new` keyword. + * + * @param r integer 0-255 inclusive + * @param g integer 0-255 inclusive + * @param b integer 0-255 inclusive + * @param [a] float 0 - 1 inclusive + * @returns a SassColor instance. + */ + (r: number, g: number, b: number, a?: number): Color; + + /** + * Constructs a new Sass color given a 4 byte number. Do not invoke with the `new` keyword. + * + * If a single number is passed it is assumed to be a number that contains + * all the components which are extracted using bitmasks and bitshifting. + * + * @param hexN A number that is usually written in hexadecimal form. E.g. 0xff0088cc. + * @returns a Sass Color instance. + * @example + * // Comparison with byte array manipulation + * let a = new ArrayBuffer(4); + * let hexN = 0xCCFF0088; // 0xAARRGGBB + * let a32 = new Uint32Array(a); // Uint32Array [ 0 ] + * a32[0] = hexN; + * let a8 = new Uint8Array(a); // Uint8Array [ 136, 0, 255, 204 ] + * let componentBytes = [a8[2], a8[1], a8[0], a8[3] / 255] // [ 136, 0, 255, 0.8 ] + * let c = sass.types.Color(hexN); + * let components = [c.getR(), c.getG(), c.getR(), c.getA()] // [ 136, 0, 255, 0.8 ] + * assert.deepEqual(componentBytes, components); // does not raise. + */ + (hexN: number): Color; + } + + export const Color: ColorConstructor; + + // *** Sass Boolean *** + + export interface Boolean { + getValue(): boolean; + } + + interface BooleanConstructor { + (bool: boolean): Boolean; + TRUE: Boolean; + FALSE: Boolean; + } + + export const Boolean: BooleanConstructor; + + // *** Sass List *** + + export interface Enumerable { + getValue(index: number): Value; + setValue(index: number, value: Value): void; + getLength(): number; + } + + export interface List extends Enumerable { + getSeparator(): boolean; + setSeparator(isComma: boolean): void; + } + interface ListConstructor { + new (length: number, commaSeparator?: boolean): List; + (length: number, commaSeparator?: boolean): List; + } + export const List: ListConstructor; + + // *** Sass Map *** + + export interface Map extends Enumerable { + getKey(index: number): Value; + setKey(index: number, key: Value): void; + } + interface MapConstructor { + new (length: number): Map; + (length: number): Map; + } + export const Map: MapConstructor; + + // *** Sass Error *** + + export interface Error { + /** + * This property doesn't exist, but its presence forces the typescript + * compiler to properly type check this type. Without it, it seems to + * allow things that aren't types.Error to match it in case statements and + * assignments. + */ + readonly ___SASS_ERROR___: unique symbol; + // why isn't there a getMessage() method? + } + + interface ErrorConstructor { + /** + * An error return value for async functions. + * For synchronous functions, this can be returned or a standard error object can be thrown. + */ + new (message: string): Error; + /** + * An error return value for async functions. + * For synchronous functions, this can be returned or a standard error object can be thrown. + */ + (message: string): Error; + } + export const Error: ErrorConstructor; + + /* eslint-enable @typescript-eslint/ban-types */ + /* tslint:enable:ban-types */ +} + +// *** Top level Constants *** + +export const NULL: types.Null; +export const TRUE: types.Boolean; +export const FALSE: types.Boolean; +export const info: string; +export function render(options: Options, callback: SassRenderCallback): void; +export function renderSync(options: SyncOptions): Result; diff --git a/types/node-sass/node-sass-tests.ts b/types/node-sass/node-sass-tests.ts index 4de32d7d06..e8ae73cef7 100644 --- a/types/node-sass/node-sass-tests.ts +++ b/types/node-sass/node-sass-tests.ts @@ -1,48 +1,193 @@ import * as sass from 'node-sass'; -sass.render({ - file: '/path/to/myFile.scss', - data: 'body{background:blue; a{color:black;}}', - importer: function(url, prev, done) { - someAsyncFunction(url, prev, function(result) { - if (result == null) { - // return null to opt out of handling this path - // compiler will fall to next importer in array (or its own default) - return null; - } - // only one of them is required, see section Sepcial Behaviours. - done({ file: result.path }); - done({ contents: result.data }); - }); - }, - includePaths: ['lib/', 'mod/'], - outputStyle: 'compressed' -}, function(error, result) { // node-style callback from v3.0.0 onwards +console.log(sass.info); + +const syncImporter: sass.SyncImporter = function(url, prev) { + if (url.startsWith('!')) { + return sass.NULL; + } + if (url.endsWith('?')) { + return sass.types.Error("cannot question mark"); + } + console.log(typeof this.callback); // "undefined" + return { file: [prev, url].join('/') }; +}; + +const asyncImporter: sass.AsyncImporter = function(url, prev, done) { + if (url.startsWith('!')) { + // shouldn't really call twice, just checking for compiler validity + done(null); + done(sass.NULL); + } + if (url.endsWith('?')) { + // shouldn't really call twice, just checking for compiler validity + done(new sass.types.Error('Cannot accept this file')); + done(new Error('Cannot accept this file')); + } else { + console.log(this.options.file); // "string" + console.log(typeof this.callback); // "function" + done({ file: [prev, url].join('/') }); + } +}; + +const anotherAsyncImporter: sass.AsyncImporter = (url, prev, done) => { + someAsyncFunction(url, prev, (result) => { + if (result == null) { + // return null to opt out of handling this path + // compiler will fall to next importer in array (or its own default) + done(null); + } + // only one of them is required, see section Special Behaviors. + done({ file: result.path }); + done({ contents: result.data }); + }); +}; + +const handleAsyncResult: sass.SassRenderCallback = (error, result) => { // node-style callback from v3.0.0 onwards if (error) { console.log(error.status, error.column, error.message, error.line); - } - else { + } else { console.log(result.stats); console.log(result.css.toString()); console.log(result.map.toString()); // or better console.log(JSON.stringify(result.map)); // note, JSON.stringify accepts Buffer too } -}); +}; + +const syncFunction: Record = { + "pow($base, $exp)"($base, $exp) { + console.log(this.options.file); // "string" + console.log(typeof this.callback); // "undefined" + if ($base instanceof sass.types.Number && $exp instanceof sass.types.Number) { + if ($base.getUnit() !== "" || $exp.getUnit() !== "") { + throw new Error("Cannot have units in an exponent"); + } + return new sass.types.Number(Math.pow($base.getValue(), $exp.getValue())); + } else { + throw new Error("Number expected"); + } + } +}; + +const syncVarArg: Record = { + "add-all($n1, $n2, $ns...)"($n1, $n2, $ns) { + if (!($n1 instanceof sass.types.Number)) { + throw new Error("Expected a number"); + } + if (!($n2 instanceof sass.types.Number)) { + throw new Error("Expected a number"); + } + const unit = $n1.getUnit(); + if ($n2.getUnit() !== unit) { + throw new Error("units don't match"); + } + let accum = $n1.getValue() + $n2.getValue(); + $ns.forEach(($n) => { + if (!($n instanceof sass.types.Number)) { + throw new Error("Expected a number"); + } + if ($n.getUnit() !== unit) { + throw new Error("units don't match"); + } + accum = accum + $n.getValue(); + }); + return sass.types.Number(accum, unit); + } +}; + +const syncFunctions: Record = {...syncFunction, ...syncVarArg}; + +const asyncFunction: Record = { + "pow-async($base, $exp)"($base, $exp, done) { + console.log(this.options.file); // "string" + console.log(typeof this.callback); // "function" + if ($base instanceof sass.types.Number && $exp instanceof sass.types.Number) { + if ($base.getUnit() !== "" || $exp.getUnit() !== "") { + done(new sass.types.Error("Cannot have units in an exponent")); + } + done(new sass.types.Number(Math.pow($base.getValue(), $exp.getValue()))); + } else { + done(new sass.types.Error("Number expected")); + } + } +}; + +const asyncVarArg: Record = { + "add-all-async($n1, $n2, $ns...)"($n1, $n2, $ns, done) { + if (!($n1 instanceof sass.types.Number)) { + done(new sass.types.Error("Expected a number")); + return; + } + if (!($n2 instanceof sass.types.Number)) { + done(new sass.types.Error("Expected a number")); + return; + } + const unit = $n1.getUnit(); + if ($n2.getUnit() !== unit) { + done(new sass.types.Error("units don't match")); + return; + } + let accum = $n1.getValue() + $n2.getValue(); + for (const $n of $ns) { + if (!($n instanceof sass.types.Number)) { + done(new sass.types.Error("Expected a number")); + return; + } + if ($n.getUnit() !== unit) { + done(new sass.types.Error("units don't match")); + return; + } + accum = accum + $n.getValue(); + } + done(sass.types.Number(accum, unit)); + } +}; + +const asyncFunctions: Record = {...asyncFunction, ...asyncVarArg}; + +const functions: sass.FunctionDeclarations = {...syncFunctions, ...asyncFunctions}; + +sass.render({ + file: '/path/to/myFile.scss', + data: 'body{background:blue; a{color:black;}}', + functions, + importer: [anotherAsyncImporter, asyncImporter, syncImporter], + includePaths: ['lib/', 'mod/'], + outputStyle: 'compressed' +}, handleAsyncResult); + // OR + +sass.render({ + file: '/path/to/myFile.scss', + data: 'body{background:blue; a{color:black;}}', + importer: asyncImporter, + includePaths: ['lib/', 'mod/'], + outputStyle: 'compressed' +}, handleAsyncResult); + +// OR + +sass.render({ + file: '/path/to/myFile.scss', + data: 'body{background:blue; a{color:black;}}', + importer: syncImporter, + includePaths: ['lib/', 'mod/'], + outputStyle: 'compressed' +}, handleAsyncResult); + +// OR + const result = sass.renderSync({ file: '/path/to/file.scss', data: 'body{background:blue; a{color:black;}}', outputStyle: 'compressed', + functions: syncFunctions, outFile: '/to/my/output.css', sourceMap: true, // or an absolute or relative (to outFile) path sourceMapRoot: '.', - importer: function(url, prev) { - if (url.startsWith('!')) { - return new Error('Cannot accept this file'); - } - return { file: [prev, url].join('/') }; - }, + importer: syncImporter, }); console.log(result.css); @@ -50,6 +195,104 @@ console.log(result.map); console.log(result.stats); function someAsyncFunction(url: string, prev: string, callback: (result: { path: string; data: string }) => void): void { } -function someSyncFunction(url: string, prev: string): { path: string; data: string } { - return null; + +function sameType(v1: V, v2: V): boolean { + return v1.constructor === v2.constructor; } + +// function-based Constructors and instance methods for types +const true1 = sass.types.Boolean(true); +true1.getValue(); // true +const true2 = sass.types.Boolean.TRUE; +const true3 = sass.TRUE; +sameType(true2, true3); +true2 === true3; // true +const false1 = sass.types.Boolean(false); +const false2 = sass.types.Boolean.FALSE; +const false3 = sass.FALSE; +false2 === false3; // true +false1.getValue(); // false +const null1 = sass.types.Null(); +const null2 = sass.types.Null.NULL; +const null3 = sass.NULL; +sameType(null2, null3); +null1 === null2; // true +null1 === null3; // true +const ident = sass.types.String("x"); +ident.getValue(); // 'x' +const stringQuoted = sass.types.String("'x'"); +stringQuoted.getValue(); // '\'x\'' +const number = sass.types.Number(5); +number.getUnit(); // "" +number.getValue(); // 5 +const dimension = sass.types.Number(5, "px"); +dimension.getUnit(); // "px" +const redOpaque = sass.types.Color(240, 15, 0); +redOpaque.getR(); // 240 +redOpaque.getG(); // 15 +redOpaque.getB(); // 0 +redOpaque.getA(); // 1 +const redTranslucent = sass.types.Color(240, 15, 0, 0.5); +redTranslucent.getA(); // 0.5 +const redOpaque2 = sass.types.Color(0xF00F00FF); +redOpaque2.getR(); // 240 +redOpaque2.getG(); // 15 +redOpaque2.getB(); // 0 +redOpaque2.getA(); // 1 +const redTranslucent2 = sass.types.Color(0xF00F007F); +redTranslucent.getA(); // 0.5 +const spaceList1 = sass.types.List(1); +spaceList1.getLength(); // 1 +spaceList1.getSeparator(); // false +spaceList1.setValue(0, ident); +spaceList1.setValue(0, true1); +spaceList1.setValue(0, false1); +spaceList1.setValue(0, null1); +spaceList1.setValue(0, dimension); +spaceList1.setValue(0, redOpaque); +spaceList1.getValue(0) === redOpaque; // true +const spaceList2 = sass.types.List(1, false); +spaceList2.setValue(0, sass.types.String("s")); +const commaList1 = sass.types.List(2, true); +commaList1.getLength(); // 2 +commaList1.getSeparator(); // true (it's a comma) +commaList1.setValue(0, spaceList1); +commaList1.setValue(2, spaceList2); +const map1 = sass.types.Map(2); +map1.getLength(); // 2 +map1.setKey(0, ident); +map1.setValue(0, spaceList1); +ident === map1.getKey(0); // true +spaceList1 === map1.getValue(1); // true +sameType(ident, map1.getKey(0)); // true +const error = new sass.types.Error("message"); + +function valuesOf(enumerable: sass.types.Enumerable): sass.types.Value[] { + const values = new Array(); + for (let i = 0; i < enumerable.getLength(); i++) { + values.push(enumerable.getValue(i)); + } + return values; +} + +let arr = valuesOf(map1); +console.dir(arr); +arr = valuesOf(commaList1); +console.dir(arr); + +// new-based Constructors +// boolean and null raise a runtime error if constructed with new. +// const newTrue = new sass.types.Boolean(true); +// const newFalse = new sass.types.Boolean(false); +// const newNull = new sass.types.Null(); +const newIdent = new sass.types.String("x"); +const newNumber = new sass.types.Number(5); +const newDimension = new sass.types.Number(5, "px"); +const newRedOpaque = new sass.types.Color(240, 15, 0); +const newRedTranslucent = new sass.types.Color(240, 15, 0, 0.5); +const newRedOpaque2 = new sass.types.Color(0xF00F00FF); +const newSpaceList1 = new sass.types.List(1); +const newSpaceList2 = new sass.types.List(1, false); +const newCommaList1 = new sass.types.List(2, true); +const newMap1 = new sass.types.Map(2); +const newError = new sass.types.Error("message"); diff --git a/types/node-sass/tsconfig.json b/types/node-sass/tsconfig.json index a1e4cdb079..172d6270c7 100644 --- a/types/node-sass/tsconfig.json +++ b/types/node-sass/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ diff --git a/types/node-sass/tslint.json b/types/node-sass/tslint.json index a41bf5d19a..0b6d65eeac 100644 --- a/types/node-sass/tslint.json +++ b/types/node-sass/tslint.json @@ -1,79 +1,9 @@ { "extends": "dtslint/dt.json", "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false + // We don't want to export the Constructor interfaces + // and I can't figure out how to disable this lint using + // `export {}` + "strict-export-declare-modifiers": false } } diff --git a/types/npm/index.d.ts b/types/npm/index.d.ts index 21ee933e59..066a932440 100644 --- a/types/npm/index.d.ts +++ b/types/npm/index.d.ts @@ -167,8 +167,8 @@ declare namespace NPM { Conf: ConfigStatic; defs: ConfigDefs; - get(setting: string): string; - set(setting: string, value: string): void; + get(setting: string): any; + set(setting: string, value: any): void; loadPrefix(cb: ErrorCallback): void; loadCAFile(caFilePath: string, cb: ErrorCallback): void; diff --git a/types/npm/npm-tests.ts b/types/npm/npm-tests.ts index 8ca5f01887..460e6f450a 100644 --- a/types/npm/npm-tests.ts +++ b/types/npm/npm-tests.ts @@ -22,4 +22,6 @@ npm.load({}, function (er) { npm.on("log", function (message: string) { console.log(message); }); + + npm.config.set('audit', false); }) diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 47943e34b6..8e19d41cb5 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -23053,7 +23053,7 @@ declare namespace Excel { copy(positionType?: "None" | "Before" | "After" | "Beginning" | "End", relativeTo?: Excel.Worksheet): Excel.Worksheet; /** * - * Deletes the worksheet from the workbook. + * Deletes the worksheet from the workbook. Note that if the worksheet's visibility is set to "VeryHidden", the delete operation will fail with a GeneralException. * * [Api set: ExcelApi 1.1] */ diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 6c38874334..eec8df60c0 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -22309,7 +22309,7 @@ declare namespace Excel { copy(positionType?: "None" | "Before" | "After" | "Beginning" | "End", relativeTo?: Excel.Worksheet): Excel.Worksheet; /** * - * Deletes the worksheet from the workbook. + * Deletes the worksheet from the workbook. Note that if the worksheet's visibility is set to "VeryHidden", the delete operation will fail with a GeneralException. * * [Api set: ExcelApi 1.1] */ diff --git a/types/parse-unit/index.d.ts b/types/parse-unit/index.d.ts index 238f3cfc06..7b37d0e64b 100644 --- a/types/parse-unit/index.d.ts +++ b/types/parse-unit/index.d.ts @@ -3,5 +3,5 @@ // Definitions by: Jack Works // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function parse(value: string): [number, string]; +declare function parse(value: string | number): [number, string]; export = parse; diff --git a/types/parse-unit/parse-unit-tests.ts b/types/parse-unit/parse-unit-tests.ts index dd5dcb7e9f..5cd4b180b8 100644 --- a/types/parse-unit/parse-unit-tests.ts +++ b/types/parse-unit/parse-unit-tests.ts @@ -2,3 +2,7 @@ import parse = require('parse-unit'); const [number, length] = parse('10px'); number === 50; length === 'px'; + +parse(10).length === 2; +parse(10)[0] === 10; +parse(10)[1] === ''; diff --git a/types/react-aria-menubutton/index.d.ts b/types/react-aria-menubutton/index.d.ts index 157fdff642..dc3d975d64 100644 --- a/types/react-aria-menubutton/index.d.ts +++ b/types/react-aria-menubutton/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-aria-menubutton 6.1 +// Type definitions for react-aria-menubutton 6.2 // Project: https://github.com/davidtheclark/react-aria-menubutton // Definitions by: Muhammad Fawwaz Orabi // Chris Rohlfs @@ -100,7 +100,7 @@ export interface MenuItemProps * If value has a value, it will be passed to the onSelection handler * when the `MenuItem` is selected */ - value?: string | boolean | number; + value?: any; /** * If `text` has a value, its first letter will be the letter a user can diff --git a/types/react-aria-menubutton/react-aria-menubutton-tests.tsx b/types/react-aria-menubutton/react-aria-menubutton-tests.tsx index f284e932a4..e3b543103a 100644 --- a/types/react-aria-menubutton/react-aria-menubutton-tests.tsx +++ b/types/react-aria-menubutton/react-aria-menubutton-tests.tsx @@ -121,3 +121,18 @@ closeMenu("", { focusMenu: true }); openMenu(""); openMenu("", { focusMenu: true }); + +class ObjectMenuItem extends React.Component { + render() { + const itemValue = { name: "Test name", label: "Only item to select" }; + return ( + console.log(value.name)}> +
  • + {itemValue.label} +
  • +
    + ); + } +} + +ReactDOM.render(, document.body); diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 3607086e06..7a6bebe1c2 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -114,7 +114,7 @@ export interface HeaderProps { } export interface Components { - event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + event?: React.ComponentType; eventWrapper?: React.ComponentType; eventContainerWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; @@ -157,6 +157,11 @@ export interface ToolbarProps { children?: React.ReactNode; } +export interface EventProps { + event: T; + title: string; +} + export interface EventWrapperProps { // https://github.com/intljusticemission/react-big-calendar/blob/27a2656b40ac8729634d24376dff8ea781a66d50/src/TimeGridEvent.js#L28 style?: React.CSSProperties & { xOffset: number }; diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index f81bbf4021..19c842f5a2 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -17,7 +17,7 @@ import { DOMAttributes, DOMElement, ReactNode, ReactPortal } from 'react'; -export function findDOMNode(instance: ReactInstance): Element | null | Text; +export function findDOMNode(instance: ReactInstance | null | undefined): Element | null | Text; export function unmountComponentAtNode(container: Element): boolean; export function createPortal(children: ReactNode, container: Element, key?: null | string): ReactPortal; diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index 46274e3ffd..20bfda53ea 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -30,6 +30,8 @@ describe('ReactDOM', () => { const rootElement = document.createElement('div'); ReactDOM.render(React.createElement('div'), rootElement); ReactDOM.findDOMNode(rootElement); + ReactDOM.findDOMNode(null); + ReactDOM.findDOMNode(undefined); }); it('createPortal', () => { diff --git a/types/react-dom/v15/index.d.ts b/types/react-dom/v15/index.d.ts index 8a22fd9bc2..653469b277 100644 --- a/types/react-dom/v15/index.d.ts +++ b/types/react-dom/v15/index.d.ts @@ -15,7 +15,7 @@ import { DOMAttributes, DOMElement } from 'react'; -export function findDOMNode(instance: ReactInstance): E; +export function findDOMNode(instance: ReactInstance | null | undefined): E; export function findDOMNode(instance: ReactInstance): Element; export function render

    , T extends Element>( diff --git a/types/react-dom/v15/react-dom-tests.ts b/types/react-dom/v15/react-dom-tests.ts index 865d74e386..5f5b149594 100644 --- a/types/react-dom/v15/react-dom-tests.ts +++ b/types/react-dom/v15/react-dom-tests.ts @@ -25,6 +25,8 @@ describe('ReactDOM', () => { const rootElement = document.createElement('div'); ReactDOM.render(React.createElement('div'), rootElement); ReactDOM.findDOMNode(rootElement); + ReactDOM.findDOMNode(null); + ReactDOM.findDOMNode(undefined); }); }); diff --git a/types/react-draft-wysiwyg/index.d.ts b/types/react-draft-wysiwyg/index.d.ts index 7b9b3577d8..46fab16511 100644 --- a/types/react-draft-wysiwyg/index.d.ts +++ b/types/react-draft-wysiwyg/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/jpuri/react-draft-wysiwyg#readme // Definitions by: imechZhangLY // brunoMaurice +// ldanet // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,9 +19,9 @@ export class ContentBlock extends Draft.ContentBlock {} export class SelectionState extends Draft.SelectionState {} export interface EditorProps { - onChange?(contentState: ContentState): RawDraftContentState; + onChange?(contentState: RawDraftContentState): void; onEditorStateChange?(editorState: EditorState): void; - onContentStateChange?(contentState: ContentState): RawDraftContentState; + onContentStateChange?(contentState: RawDraftContentState): void; initialContentState?: RawDraftContentState; defaultContentState?: RawDraftContentState; contentState?: RawDraftContentState; diff --git a/types/react-draft-wysiwyg/test/uncontrolled-raw-draft-content-state.tsx b/types/react-draft-wysiwyg/test/uncontrolled-raw-draft-content-state.tsx new file mode 100644 index 0000000000..4118ce2d09 --- /dev/null +++ b/types/react-draft-wysiwyg/test/uncontrolled-raw-draft-content-state.tsx @@ -0,0 +1,48 @@ +// From https://github.com/jpuri/react-draft-wysiwyg/blob/master/docs/src/components/Docs/Props/EditorStateProp/index.js#L125 + +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import { Editor, RawDraftContentState } from "react-draft-wysiwyg"; + +class UncontrolledEditor extends React.Component< + {}, + { contentState: RawDraftContentState } +> { + constructor(props: any) { + super(props); + this.state = { + contentState: JSON.parse(`{ + "entityMap":{}, + "blocks":[{ + "key":"1ljs", + "text":"Initializing from content state", + "type":"unstyled", + "depth":0, + "inlineStyleRanges":[], + "entityRanges":[], + "data":{} + }] + }`) + }; + } + + onContentStateChange = (contentState: RawDraftContentState) => { + this.setState({ + contentState + }); + } + + render() { + const { contentState } = this.state; + return ( + + ); + } +} + +ReactDOM.render(, document.getElementById("target")); diff --git a/types/react-draft-wysiwyg/tsconfig.json b/types/react-draft-wysiwyg/tsconfig.json index 35720c1979..0218edab95 100644 --- a/types/react-draft-wysiwyg/tsconfig.json +++ b/types/react-draft-wysiwyg/tsconfig.json @@ -24,6 +24,7 @@ "test/basic-controlled-tests.tsx", "test/basic-tests.tsx", "test/custom-toolbar-tests.tsx", - "test/focus-blur-callbacks-tests.tsx" + "test/focus-blur-callbacks-tests.tsx", + "test/uncontrolled-raw-draft-content-state.tsx" ] } diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index a57da91307..d547396a11 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -21,7 +21,7 @@ export interface Options { */ animationData: any; rendererSettings?: { - preserveAspectRatio?: boolean; + preserveAspectRatio?: string; /** * The canvas context */ diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 99865ac3be..0cee14dfd2 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7662,6 +7662,9 @@ export interface PanResponderStatic { export interface Rationale { title: string; message: string; + buttonPositive: string; + buttonNegative?: string; + buttonNeutral?: string; } export type Permission = diff --git a/types/react-navigation/index.d.ts b/types/react-navigation/index.d.ts index df678c4ed9..860d54523e 100644 --- a/types/react-navigation/index.d.ts +++ b/types/react-navigation/index.d.ts @@ -31,6 +31,7 @@ // Fellipe Chagas // Deniss Borisovs // Kenneth Skovhus +// Aaron Rosen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -623,7 +624,7 @@ export interface NavigationEventSubscription { } export interface NavigationEventsProps extends ViewProps { - navigation?: NavigationNavigator; + navigation?: NavigationScreenProp; onWillFocus?: NavigationEventCallback; onDidFocus?: NavigationEventCallback; onWillBlur?: NavigationEventCallback; @@ -1367,3 +1368,5 @@ export interface SafeAreaViewProps extends ViewProps { } export const SafeAreaView: React.ComponentClass; + +export const NavigationContext: React.Context>; diff --git a/types/react-navigation/react-navigation-tests.tsx b/types/react-navigation/react-navigation-tests.tsx index d30714fadb..777a8fa9f3 100644 --- a/types/react-navigation/react-navigation-tests.tsx +++ b/types/react-navigation/react-navigation-tests.tsx @@ -42,6 +42,7 @@ import { HeaderBackButton, Header, NavigationContainer, + NavigationContext, NavigationParams, NavigationPopAction, NavigationPopToTopAction, @@ -681,3 +682,14 @@ const ViewWithNavigationEvents = ( onDidBlur={console.log} /> ); + +// Test NavigationContext +const componentWithNavigationContext = ( + + { + navigationContext => ( + + ) + } + +); diff --git a/types/react/index.d.ts b/types/react/index.d.ts index bc9c4ce342..97adab18d4 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -807,6 +807,14 @@ declare namespace React { * @see https://reactjs.org/docs/hooks-reference.html#usestate */ function useState(initialState: S | (() => S)): [S, Dispatch>]; + // convenience overload when first argument is ommitted + /** + * Returns a stateful value, and a function to update it. + * + * @version 16.8.0 + * @see https://reactjs.org/docs/hooks-reference.html#usestate + */ + function useState(): [S | undefined, Dispatch>]; /** * An alternative to `useState`. * @@ -894,6 +902,20 @@ declare namespace React { */ // TODO (TypeScript 3.0): function useRef(initialValue: T|null): RefObject; + // convenience overload for potentially undefined initialValue / call with 0 arguments + // has a default to stop it from defaulting to {} instead + /** + * `useRef` returns a mutable ref object whose `.current` property is initialized to the passed argument + * (`initialValue`). The returned object will persist for the full lifetime of the component. + * + * Note that `useRef()` is useful for more than the `ref` attribute. It’s handy for keeping any mutable + * value around similar to how you’d use instance fields in classes. + * + * @version 16.8.0 + * @see https://reactjs.org/docs/hooks-reference.html#useref + */ + // TODO (TypeScript 3.0): + function useRef(): MutableRefObject; /** * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside @@ -958,7 +980,8 @@ declare namespace React { * @version 16.8.0 * @see https://reactjs.org/docs/hooks-reference.html#usememo */ - function useMemo(factory: () => T, deps: DependencyList): T; + // allow undefined, but don't make it optional as that is very likely a mistake + function useMemo(factory: () => T, deps: DependencyList | undefined): T; /** * `useDebugValue` can be used to display a label for custom hooks in React DevTools. * diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index 26ff634e89..70ea9a0ce7 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -100,9 +100,46 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { // inline object, to (manually) check if autocomplete works React.useReducer(reducer, { age: 42, name: 'The Answer' }); - // make sure this is not going to the |null overload - // $ExpectType MutableRefObject - const didLayout = React.useRef(false); + // test useRef and its convenience overloads + // $ExpectType MutableRefObject + React.useRef(0); + + // these are not very useful (can't assign anything else to .current) + // but it's the only safe way to resolve them + // $ExpectType MutableRefObject + React.useRef(null); + // $ExpectType MutableRefObject + React.useRef(undefined); + + // |null convenience overload + // it should _not_ be mutable if the generic argument doesn't include null + // $ExpectType RefObject + React.useRef(null); + // but it should be mutable if it does (i.e. is not the convenience overload) + // $ExpectType MutableRefObject + React.useRef(null); + + // |undefined convenience overload + // with no contextual type or generic argument it should default to undefined only (not {} or unknown!) + // $ExpectType MutableRefObject + React.useRef(); + // $ExpectType MutableRefObject + React.useRef(); + // don't just accept a potential undefined if there is a generic argument + // $ExpectError + React.useRef(undefined); + // make sure once again there's no |undefined if the initial value doesn't either + // $ExpectType MutableRefObject + React.useRef(1); + // and also that it is not getting erased if the parameter is wider + // $ExpectType MutableRefObject + React.useRef(1); + + // should be contextually typed + const a: React.MutableRefObject = React.useRef(undefined); + const b: React.MutableRefObject = React.useRef(); + const c: React.MutableRefObject = React.useRef(null); + const d: React.RefObject = React.useRef(null); const id = React.useMemo(() => Math.random(), []); React.useImperativeHandle(ref, () => ({ id }), [id]); @@ -110,6 +147,10 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { // $ExpectError React.useImperativeMethods(ref, () => ({}), [id]); + // make sure again this is not going to the |null convenience overload + // $ExpectType MutableRefObject + const didLayout = React.useRef(false); + React.useLayoutEffect(() => { setState(1); setState(prevState => prevState - 1); @@ -140,6 +181,29 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { React.useDebugValue(id, value => value.toFixed()); React.useDebugValue(id); + // allow passing an explicit undefined + React.useMemo(() => {}, undefined); + // but don't allow it to be missing + // $ExpectError + React.useMemo(() => {}); + + // useState convenience overload + // default to undefined only (not that useful, but type-safe -- no {} or unknown!) + // $ExpectType undefined + React.useState()[0]; + // $ExpectType number | undefined + React.useState()[0]; + // default overload + // $ExpectType number + React.useState(0)[0]; + // $ExpectType undefined + React.useState(undefined)[0]; + // make sure the generic argument does reject actual potentially undefined inputs + // $ExpectError + React.useState(undefined)[0]; + + // useReducer convenience overload + return React.useCallback(() => didLayout.current, []); } diff --git a/types/sass-webpack-plugin/index.d.ts b/types/sass-webpack-plugin/index.d.ts index df589ca034..1299429790 100644 --- a/types/sass-webpack-plugin/index.d.ts +++ b/types/sass-webpack-plugin/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jalkoby/sass-webpack-plugin // Definitions by: AEPKILL // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.6 +// TypeScript Version: 2.7 import { Options } from 'node-sass'; import { Plugin } from 'webpack'; diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 5d1131684c..d89dac0d4a 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3286,6 +3286,11 @@ declare namespace sequelize { * if true, it will also eager load the relations of the child models, recursively. */ nested?: boolean; + + /** + * If true, runs a separate query to fetch the associated instances, only supported for hasMany associations + */ + separate?: boolean; } /** @@ -6510,6 +6515,16 @@ declare namespace sequelize { */ logging?: Function; + /** + * Specify the parent transaction so that this transaction is nested or a save point within the parent + */ + transaction?: Transaction; + + /** + * Sets the constraints to be deferred or immediately checked. + */ + deferrable?: Deferrable[keyof Deferrable]; + } // diff --git a/types/tern/lib/tern/index.d.ts b/types/tern/lib/tern/index.d.ts index 0e48925914..7ecb4ac73e 100644 --- a/types/tern/lib/tern/index.d.ts +++ b/types/tern/lib/tern/index.d.ts @@ -164,17 +164,20 @@ export interface BaseQuery { docFormat?: "full"; } +export interface BaseQueryWithFile extends BaseQuery { + /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ + file: string; +} + export interface Position { ch: number; line: number; } /** Asks the server for a set of completions at the given point. */ -export interface CompletionsQuery extends BaseQuery { +export interface CompletionsQuery extends BaseQueryWithFile { /** Asks the server for a set of completions at the given point. */ type: "completions"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location to complete at. */ end: number | Position; /** Whether to include the types of the completions in the result data. Default `false` */ @@ -233,11 +236,9 @@ export interface CompletionsQueryResult { } /** Query the type of something. */ -export interface TypeQuery extends BaseQuery { +export interface TypeQuery extends BaseQueryWithFile { /** Query the type of something. */ type: "type"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location of the expression. */ end: number | Position; /** Specify the location of the expression. */ @@ -282,7 +283,7 @@ export interface TypeQueryResult { * type is not an object or function (other types don’t store their definition site), * it will fail to return useful information. */ -export interface DefinitionQuery extends BaseQuery { +export interface DefinitionQuery extends BaseQueryWithFile { /** * Asks for the definition of something. This will try, for a variable or property, * to return the point at which it was defined. If that fails, or the chosen @@ -292,8 +293,6 @@ export interface DefinitionQuery extends BaseQuery { * it will fail to return useful information. */ type: "definition"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location of the expression. */ end: number | Position; /** Specify the location of the expression. */ @@ -320,11 +319,9 @@ export interface DefinitionQueryResult { } /** Get the documentation string and URL for a given expression, if any. */ -export interface DocumentationQuery extends BaseQuery { +export interface DocumentationQuery extends BaseQueryWithFile { /** Get the documentation string and URL for a given expression, if any. */ type: "documentation"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location of the expression. */ end: number | Position; /** Specify the location of the expression. */ @@ -341,11 +338,9 @@ export interface DocumentationQueryResult { } /** Used to find all references to a given variable or property. */ -export interface RefsQuery extends BaseQuery { +export interface RefsQuery extends BaseQueryWithFile { /** Used to find all references to a given variable or property. */ type: "refs"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location of the expression. */ end: number | Position; /** Specify the location of the expression. */ @@ -365,11 +360,9 @@ export interface RefsQueryResult { } /** Rename a variable in a scope-aware way. */ -export interface RenameQuery extends BaseQuery { +export interface RenameQuery extends BaseQueryWithFile { /** Rename a variable in a scope-aware way. */ type: "rename"; - /** may hold either a filename, or a string in the form "#N", where N should be an integer referring to one of the files included in the request */ - file: string; /** Specify the location of the variable. */ end: number | Position; /** Specify the location of the variable. */ @@ -467,7 +460,7 @@ export function registerPlugin(name: string, init: (server: Server, options?: Co export interface Desc { run(Server: Server, query: QueryRegistry[T]["query"], file?: File): QueryRegistry[T]["result"]; - takesfile?: boolean; + takesFile?: boolean; } /** diff --git a/types/theo/index.d.ts b/types/theo/index.d.ts index d60a797159..de15c0238a 100644 --- a/types/theo/index.d.ts +++ b/types/theo/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for theo 8.1 +// Type definitions for Theo 8.1 // Project: https://github.com/salesforce-ux/theo // Definitions by: Pete Petrash // Niko Laitinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 import { Collection, Map, List, OrderedMap } from "immutable"; @@ -35,21 +35,16 @@ export type Format = | "android.xml" | "aura.tokens"; -export function convert(options: ConvertOptions): Promise; -export function convertSync(options: ConvertOptions): string; -export function registerFormat( - name: string, - format: FormatResultFn | string -): void; -export function registerTransform( - name: string, - valueTransforms: string[] -): void; -export function registerValueTransform( - name: string, - predicate: (prop: Prop) => boolean, - transform: (prop: Prop) => string | number -): void; +export type Transform = "raw" | "ios" | "android" | "web"; + +export type ValueTransform = + | "color/rgb" + | "color/hex" + | "color/hex8rgba" + | "color/hex8argb" + | "percentage/float" + | "relative/pixel" + | "relative/pixelValue"; export type Prop = Map; export type Props = List; @@ -78,8 +73,8 @@ export interface ConvertOptions { resolveMetaAliases?: boolean; } -export interface TransformOptions { - type?: string; +export interface TransformOptions { + type?: Transform | T; file: string; data?: string; } @@ -91,3 +86,19 @@ export interface FormatOptions { transformPropName?: (name: string) => string ) => void; } + +export function convert(options: ConvertOptions): Promise; +export function convertSync(options: ConvertOptions): string; +export function registerFormat( + name: Format | T, + format: FormatResultFn | string +): void; +export function registerTransform( + name: Transform | T, + valueTransforms: ValueTransform[] | T[] +): void; +export function registerValueTransform( + name: ValueTransform | T, + predicate: (prop: Prop) => boolean, + transform: (prop: Prop) => string | number +): void; diff --git a/types/theo/tslint.json b/types/theo/tslint.json index 3db14f85ea..71ee04c4e1 100644 --- a/types/theo/tslint.json +++ b/types/theo/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } +} diff --git a/types/three/index.d.ts b/types/three/index.d.ts index 08b64250c8..f929ef2383 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -17,7 +17,6 @@ // Daniel Hritzkiv , // Apurva Ojas , // Tiger Oakes , -// Seth Kingsley , // Ethan Kay , // Methuselah96 // Dilip Ramirez @@ -25,6 +24,7 @@ // Zhang Hao // Konstantin Lukaschenko // Daniel Yim +// Philippe Suter // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 7d871cae58..e7291b9402 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -5273,13 +5273,23 @@ export class Line extends Object3D { geometry: Geometry | BufferGeometry; material: Material | Material[]; - type: "Line"; + type: "Line" | "LineLoop" | "LineSegments"; isLine: true; computeLineDistances(): this; raycast(raycaster: Raycaster, intersects: Intersection[]): void; } +export class LineLoop extends Line { + constructor( + geometry?: Geometry | BufferGeometry, + material?: Material | Material[] + ); + + type: "LineLoop"; + isLineLoop: true; +} + /** * @deprecated */ @@ -5295,6 +5305,9 @@ export class LineSegments extends Line { material?: Material | Material[], mode?: number ); + + type: "LineSegments"; + isLineSegments: true; } export class Mesh extends Object3D {