diff --git a/README.md b/README.md
index a9be0471a1..026994fdd5 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
Also see the [definitelytyped.org](http://definitelytyped.org) website, although information in this README is more up-to-date.
-*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [Korean!](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md)*
+*You can also read this README in [Spanish](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md), [Korean](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md), and [Russian](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ru.md)!*
## What are declaration files?
@@ -169,10 +169,10 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN
#### Lint
-All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
+All new packages must be linted. To lint a package, add a `tslint.json` to that package containing
```js
-{
- "extends": "dtslint/dt.json"
+{
+ "extends": "dtslint/dt.json"
}
```
diff --git a/README.ru.md b/README.ru.md
new file mode 100644
index 0000000000..b90bdeac7c
--- /dev/null
+++ b/README.ru.md
@@ -0,0 +1,353 @@
+
+
+# DefinitelyTyped [](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
+
+[](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+
+> Репозиторий для *высококачественных* определений типов TypeScript.
+
+Также посетите веб-сайт [definitelytyped.org](http://definitelytyped.org), хотя информация в этом README более свежая.
+
+*Вы также можете прочитать этот README на [английском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.md), [испанском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.es.md) and [корейском](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/README.ko.md).*
+
+## Что такое файлы декларации (файлы описания/объявления типов)?
+
+Смотрите [руководство по TypeScript](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
+
+## Как их получить?
+
+### npm
+
+Это предпочтительный метод. Это доступно только для пользователей TypeScript 2.0+. Например:
+
+```sh
+npm install --save-dev @types/node
+```
+
+Затем типы должны автоматически включаться компилятором.
+Подробнее смотрите в [справочнике](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
+
+Для пакета NPM "foo", описания будут находиться в "@types/foo".
+Если вы не можете найти свой пакет, ищите его в [TypeSearch](https://microsoft.github.io/TypeSearch/).
+
+Если вы все еще не можете найти его, проверьте [включает](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) ли пакет собственную типизацию.
+Обычно это отражается в поле `"types"` или `"typings"` файла `package.json`, или просто ищите любые файлы ".d.ts" в пакете и вручную включайте их в `/// `.
+
+
+### Другие методы
+
+Эти методы могут быть использованы TypeScript 1.0.
+
+* [Typings](https://github.com/typings/typings)
+* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (используйте предпочтительные альтернативы, публикация типа nuget DT отключена)
+* Вручную загрузите из ветки `master` этого репозитория
+
+Возможно, вам придется добавить ручные [ссылки](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
+
+
+## Как я могу внести свой вклад?
+
+DefinitelyTyped работает только благодаря вкладу таких пользователей, как вы!
+
+### Тестирование
+
+Прежде чем поделиться своим улучшением с миром, используйте его сами.
+
+#### Тестирование редактирования существующего пакета
+
+Для добавления новых функций вы можете использовать [разрешение модулей](http://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
+Вы также можете напрямую редактировать типы в `node_modules/@types/foo/index.d.ts`, или скопировать их оттуда и выполнить следующие шаги.
+
+
+#### Тестирование ногово пакета
+
+Добавьте к вашему `tsconfig.json`:
+
+```json
+"baseUrl": "types",
+"typeRoots": ["types"],
+```
+
+(Вы также можете использовать `src/types`.)
+Создайте `types/foo/index.d.ts` содержащие объявления для модуля "foo".
+Теперь вы сможете импортировать из `"foo"` в свой код, и он будет направлен к новому определению типа.
+Затем запустите сборку (build) *и* запустите код, чтобы убедиться, что ваше определение типа действительно соответствует тому, что происходит во время выполнения.
+После того как вы проверили свои определения с реальным кодом, создайте [Запрос на принятие изменений (PR)](#make-a-pull-request)
+и следуйте инструкциям [чтобы отредактировать существующий](#edit-an-existing-package) или
+[создать новый пакет](#create-a-new-package).
+
+
+### Запрос на принятие изменений (PR)
+
+После того, как вы проверили ваш пакет, вы можете поделиться им с DefinitelyTyped.
+
+Во-первых, [разветвите](https://guides.github.com/activities/forking/) этот репозиторий, установите [node](https://nodejs.org/), и запустите `npm install`.
+
+
+#### Изменение существующего пакета
+
+* `cd types/my-package-to-edit`
+* Внесите изменения. Не забудьте отредактировать тесты.
+ Если вы вносите критические изменения, не забудьте [обновить основную версию](#i-want-to-update-a-package-to-a-new-major-version).
+* Вы также можете добавить себя в раздел "Definitions by" заголовка пакета.
+ * Это приведет к тому, что вы будете уведомлены (через ваше имя пользователя GitHub) о том, что кто-то делает запрос на принятие изменений (PR) или проблему с пакетом.
+ * Сделайте это, добавив свое имя в конец строки, например `// Definitions by: Alice , Bob `.
+ * Или, если есть больше людей, это может быть многострочным
+
+ ```typescript
+ // Definitions by: Alice
+ // Bob
+ // Steve
+ // John
+ ```
+
+* Если есть `tslint.json`, запустите `npm run lint package-name`. В противном случае запустите `tsc` in в директории пакета.
+
+Когда вы создаете PR для редактирования существующего пакета, `dt-bot` должен @-уведомить previous authors.
+предыдущих авторов. Если этого не произойдет, вы можете сделать это самостоятельно в комментарии, связанном с PR.
+
+
+#### Созданое нового пакета
+
+Если вы являетесь автором библиотеки и ваш пакет написан на TypeScript, [свяжите автоматически сгенерированные файлы объявлений](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) в вашем пакете, а не публикуйте в DefinitelyTyped.
+
+Если вы добавляете типизацию для пакета NPM, создайте директорию с тем же именем.
+Если пакет, для которого вы добавляете типизацию, отсутствует в NPM, убедитесь, что выбранное вами имя не конфликтует с именем пакета в NPM.
+(Вы можете использовать `npm info foo` чтобы проверить наличие пакета `foo`.)
+
+Ваш пакет должен иметь такую структуру:
+
+| Файл | Назначение |
+| ------------- | ---------------------------------------------------------------------------------------------------- |
+| index.d.ts | Содержит типизацию для пакета. |
+| foo-tests.ts | Содержит пример кода, который проверяет типизацию. Этот код *не* запускается, но он проверен на тип. |
+| tsconfig.json | Позволяет вам запускать `tsc` внутри пакета. |
+| tslint.json | Включает linting. |
+
+Создайте их, запустив `npx dts-gen --dt --name my-package-name --template module` если у вас ≥ 5.2.0, `npm install -g dts-gen` и `dts-gen --dt --name my-package-name --template module` в противном случае.
+Посмотреть все варианты на [dts-gen](https://github.com/Microsoft/dts-gen).
+
+Вы можете отредактировать `tsconfig.json` чтобы добавить новые файлы, добавить `"target": "es6"` (необходимо для асинхронных функций), добавить в `"lib"`, или добавить опцию компилятора `"jsx"`.
+
+Члены группы DefinitelyTyped регулярно следят за новыми PR, но имейте в виду, что количество других PR может замедлить ход событий.
+
+Хороший пример пакета смотрите [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js).
+
+
+#### Распространенные ошибки
+
+* Сначала следуйте советам из справочника [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html).
+* Форматирование: либо используйте все табы, либо всегда используйте 4 пробела.
+* `function sum(nums: number[]): number`: используйте `ReadonlyArray` если функция не записывает свои параметры.
+* `interface Foo { new(): Foo; }`:
+ Это определяет тип объектов, с методом `new`. Вы, вероятно, хотите объявить `declare class Foo { constructor(); }`.
+* `const Class: { new(): IClass; }`:
+ Предпочитайте использовать объявление класса `class Class { constructor(); }` вместо `new`.
+* `getMeAT(): T`:
+ Если параметр типа не отображается в типах каких-либо параметров, у вас нет универсальной функции, а просто замаскированное утверждение типа.
+ Предпочитайте использовать утверждение реального типа, например, `getMeAT() as number`.
+ Пример, где допустим параметр типа: `function id(value: T): T;`.
+ Пример, где это недопустимо: `function parseJson(json: string): T;`.
+ Исключение: `new Map()` все ОК.
+* Использование типов `Function` and `Object` почти никогда не является хорошей идеей. В 99% случаев можно указать более конкретный тип. Примеры: `(x: number) => number` для [функций](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) and `{ x: number, y: number }` для объектов. Если нет никакой уверенности в типе, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) является правильным выбором, а не `Object`. Если единственным известным фактом о типе является то, что это какой-то объект, используйте тип [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), а не `Object` или `{ [key: string]: any }`.
+* `var foo: string | any`:
+ когда `any` используется в типе объединения, результирующий тип все еще `any`. Таким образом, хотя `string` часть аннотации этого типа может _выглядеть_ полезной, на самом деле она не предлагает никакой дополнительной проверки типов по сравнению с простым использованием `any`.
+ В зависимости от намерения, приемлемыми альтернативами могут быть `any`, `string`, или `string | object`.
+
+
+#### Удаление пакета
+
+Когда пакет [объединяет](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) свои собственные типы, типы должны быть удалены из DefinitelyTyped чтобы избежать путаницы.
+
+Вы можете удалить его, запустив `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`.
+
+* `typingsPackageName`: название директории, который нужно удалить.
+* `asOfVersion`: заглушка будет опубликована в `@types/foo` с этой версией. Должна быть выше, чем любая опубликованная на данный момент версия
+* `sourceRepoURL`: Это должно указывать на репозиторий, который содержит типизации.
+* `libraryName`: описательное имя библиотеки, например, "Angular 2" вместо "angular2". (Если опущено, будет идентично "typingsPackageName".)
+
+Любые другие пакеты в DefinitelyTyped которые ссылаются на удаленный пакет, должны быть обновлены для ссылки на связанные типы. Для этого добавьте в `package.json` ссыклу `"dependencies": { "foo": "x.y.z" }`.
+
+Если пакет никогда не был в DefinitelyTyped, его не нужно добавлять в `notNeededPackages.json`.
+
+
+#### Lint
+
+Все новые пакеты должны быть проанализированы lint. Для этого добавьте `tslint.json` в этот пакет, содержащий
+
+```js
+{
+ "extends": "dtslint/dt.json"
+}
+```
+
+Это должно быть единственным содержимым в файле `tslint.json` готового проекта. Если `tslint.json` отключает правила, это потому, что это еще не исправлено. Например:
+
+```js
+{
+ "extends": "dtslint/dt.json",
+ "rules": {
+ // This package uses the Function type, and it will take effort to fix.
+ "ban-types": false
+ }
+}
+```
+
+(Чтобы указать, что правило lint действительно не применяется, используйте `// tslint:disable rule-name` или лучше, `//tslint:disable-next-line rule-name`.)
+
+Чтобы проверить, что выражение имеет заданный тип, используйте `$ExpectType`. Чтобы проверить, что выражение вызывает ошибку компиляции, используйте `$ExpectError`.
+
+```js
+// $ExpectType void
+f(1);
+
+// $ExpectError
+f("one");
+```
+
+Для получения дополнительной информации см. [dtslint](https://github.com/Microsoft/dtslint#write-tests) readme.
+
+Протестируйте, запустив `npm run lint package-name` где `package-name` - это имя вашего пакета.
+Этот скрипт использует [dtslint](https://github.com/Microsoft/dtslint).
+
+
+## Часто задаваемые вопросы
+
+#### Какая связь между этим репозиторием и пакетами `@types` в NPM?
+
+Ветвь `master` автоматически публикуется в область `@types` на NPM благодаря [types-publisher](https://github.com/Microsoft/types-publisher).
+
+#### Я отправил PR. Когда он сольется?
+
+Это зависит, но большинство запросов на получение данных будут объединены в течение недели. PR, утвержденные автором, указанным в заголовке определения, обычно объединяются быстрее; PR для новых определений займет больше времени, так как они требуют большего количества проверок от сопровождающих. Каждый PR проверяется членом команды TypeScript или DefinitelyTyped перед объединением, поэтому будьте терпеливы, так как человеческий фактор может вызвать задержки. Посмотрите на [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) чтобы увидеть, как сопровождающие работают через открытые PR.
+
+#### Мой PR слит; когда будет обновлен пакет `@types` NPM?
+
+Пакеты NPM должны обновиться в течение нескольких часов. Если прошло более 24 часов, пингуйте @RyanCavanaugh и @andy-ms в PR, чтобы расследовать.
+
+#### Я пишу определение, которое зависит от другого определения. Должен ли я использовать `` или import?
+
+Если модуль, на который вы ссылаетесь, является внешним модулем (использует `export`), используйте import.
+Если модуль, на который вы ссылаетесь, является окружающим модулем (использует `declare module`, или просто объявляет глобальные переменные), используйте ``.
+
+#### Я заметил, что у некоторых пакетов есть `package.json`.
+
+Обычно вам это не нужно. При публикации пакета мы обычно автоматически создаем `package.json`.
+`package.json` может быть включен для определения зависимостей. Вот [пример](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json).
+Мы не разрешаем определять другие поля, такие как "description", вручную.
+Кроме того, если вам нужно сослаться на более старую версию типизаций, вы должны сделать это, добавив в `package.json` строки `"dependencies": { "@types/foo": "x.y.z" }`.
+
+#### В некоторых пакетах отсутствует `tslint.json`, а в некоторых `tsconfig.json` отсутствует `"noImplicitAny": true`, `"noImplicitThis": true`, или `"strictNullChecks": true`.
+
+Тогда они не правы. Вы можете помочь, отправив PR, чтобы исправить их.
+
+#### Могу ли я запросить определение?
+
+Вот [текущие запрошенные определения](https://github.com/DefinitelyTyped/DefinitelyTyped/labels/Definition%3ARequest).
+
+#### Как насчет определений типов для DOM?
+
+Если типы являются частью веб-стандарта, они должны быть добавлены в [TSJS-lib-generator](https://github.com/Microsoft/TSJS-lib-generator) чтобы они могли стать частью `lib.dom.d.ts` по умолчанию.
+
+#### Пакет использует export `export =`, но я предпочитаю использовать импорт по умолчанию. Могу ли я изменить `export =` на `export default`?
+
+Если вы используете TypeScript 2.7 или более позднюю версию, используйте `--esModuleInterop` в вашем проекте.
+В противном случае, если импорт по умолчанию работает в вашей среде (например, Webpack, SystemJS, esm), рассмотрите возможность включения опции компилятора [`--allowSyntheticDefaultImports`](http://www.typescriptlang.org/docs/handbook/compiler-options.html).
+Не меняйте определение типа, если оно точное.
+Для пакета NPM, `export =` является точным, если `node -p 'require("foo")'` является экспортом, а `export default` является точным, если `node -p 'require("foo").default'` является экспортом.
+
+#### Я хочу использовать функции из TypeScript 2.1 или выше.
+
+В таком случае вам нужно будет добавить комментарий к последней строке заголовка вашего определения (после `// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`): `// TypeScript Version: 2.1`.
+
+#### Я хочу добавить DOM API, отсутствующий в TypeScript по умолчанию.
+
+Это может принадлежать [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). Смотрите инструкции там.
+Если стандарт все еще является черновиком, добавляйте сюда.
+Используйте имя, начинающееся с `dom-` и включите ссылку на стандарт в качестве ссылки "Project" в заголовке.
+Когда он завершает черновой режим, мы можем удалить его из DefinitelyTyped и объявить устаревшим связанный пакет `@types`.
+
+#### Я хочу обновить пакет новой старшей версии
+
+Если вы намерены продолжить обновление старой версии пакета, вы можете создать новую подпапку с текущей версией, например, `v2` и скопируйте в него существующие файлы. Если это так, вам необходимо:
+
+1. Обновите относительные пути в `tsconfig.json` а также в `tslint.json`.
+2. Добавьте правила сопоставления путей, чтобы убедиться, что тесты выполняются для предполагаемой версии.
+
+Например [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) looks like:
+
+```json
+{
+ "compilerOptions": {
+ "baseUrl": "../../",
+ "typeRoots": ["../../"],
+ "paths": {
+ "history": [ "history/v2" ]
+ },
+ },
+ "files": [
+ "index.d.ts",
+ "history-tests.ts"
+ ]
+}
+```
+
+Если в DefinitelyTyped есть другие пакеты, несовместимые с новой версией, вам нужно будет добавить сопоставления путей к старой версии. Вам также нужно будет сделать это для пакетов в зависимости от пакетов в зависимости от старой версии.
+
+Например, `react-router` зависит от `history@2`, поэтому [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) есть сопоставление пути с `"history": [ "history/v2" ]`;
+транзитивно `react-router-bootstrap` (который зависит от `react-router`) также добавляет отображение пути в свой [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json).
+
+Также, `/// ` не будет работать с отображением пути, поэтому зависимости должны использовать `import`.
+
+#### Как мне написать определения для пакетов, которые могут использоваться и глобально и в качестве модуля?
+
+Руководство TypeScript содержит отличную [общую информацию о написании определений](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), а также [этот пример файла определения](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) , в котором показано, как создать определение с использованием синтаксиса модуля в стиле ES6, а также указаны объекты, доступные для глобальной области. Этот метод демонстрируется практически в определении для [definition for big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), библиотекой, которую можно загружать глобально с помощью тега скрипта на веб-странице или импортировать с помощью импорта по требованию или в стиле ES6.
+
+Чтобы проверить, как ваше определение может использоваться как при глобальных ссылках, так и в качестве импортированного модуля, создайте тестовую папку `test`, и поместите туда два тестовых файла. Назовите один `YourLibraryName-global.test.ts` а другой `YourLibraryName-module.test.ts`. *Глобальный* тестовый файл должен использовать определение в соответствии с тем, как он будет использоваться в скрипте, загруженном на веб-страницу, где библиотека доступна в глобальной области видимости - в этом сценарии не следует указывать оператор импорта. Тестовый файл *модуля* должен использовать определение в соответствии с тем, как оно будет использоваться при импорте (включая оператор(ы) `import`). Если вы указали свойство `files` в файле `tsconfig.json`, обязательно включите оба тестовых файла. [Практический пример этого](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) также доступен в определении big.js.
+
+Обратите внимание, что не требуется полностью использовать определение в каждом тестовом файле - достаточно протестировать только глобально доступные элементы в глобальном тестовом файле и полностью выполнить определение в тестовом файле модуля, или наоборот.
+
+#### А как насчет областных пакетов?
+
+Типы для пакета с областью `@foo/bar` должны указываться в `types/foo__bar`. Обратите внимание на двойное подчеркивание.
+
+Когда `dts-gen` используется для компоновки пакета с областью действия, свойство `paths` должно быть вручную адаптировано в сгенерированном файле
+`tsconfig.json` для правильной ссылки на пакет с областью действия:
+
+```json
+{
+ "paths":{
+ "@foo/bar": ["foo__bar"]
+ }
+}
+```
+
+
+#### История файлов в GitHub выглядит неполной.
+
+GitHub не [поддерживает](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) историю файлов для переименованных файлов. Вместо этого используйте [`git log --follow`](https://www.git-scm.com/docs/git-log).
+
+#### Должен ли я добавить пустой namespace в пакет, который не экспортирует модуль для использования импорта в стиле ES6?
+
+Некоторые пакеты, такие как [chai-http](https://github.com/chaijs/chai-http), экспортируют функцию.
+
+Импорт этого модуля с импортом в стиле ES6 в форме `import * as foo from "foo";` приводит к ошибке:
+
+> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
+
+Эту ошибку можно устранить, объединив объявление функции с пустым namespace'ом с тем же именем, но это не рекомендуется.
+Это часто цитируемый [ответ с Stack Overflow](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) по этому вопросу.
+
+Более целесообразно импортировать модуль, используя `import foo = require("foo");` синтаксис или использовать импорт по умолчанию, такой как `import foo from "foo";` при использовании флага `--allowSyntheticDefaultImports`, если среда выполнения вашего модуля поддерживает схему взаимодействия для модулей не-ECMAScript как таковых.
+
+## Лицензия
+
+Этот проект лицензирован по лицензии MIT.
+
+Авторские права на файлы определений принадлежат каждому участнику, указанному в начале каждого файла определения.
+
+[](https://github.com/igrigorik/ga-beacon)
+
+[](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) В среднем пакеты публикуются на npm менее чем за 10000 секунд?
+
+[](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Был ли typescript-bot активным на DefinitelyTyped в последние два часа?
diff --git a/node-gettext/index.d.ts b/node-gettext/index.d.ts
new file mode 100644
index 0000000000..735f8db84b
--- /dev/null
+++ b/node-gettext/index.d.ts
@@ -0,0 +1,27 @@
+// Type definitions for node-gettext 2.0
+// Project: http://github.com/alexanderwallin/node-gettext
+// Definitions by: Sameer K.C.
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+export = GetText;
+declare class GetText {
+ constructor(options?: { debug: boolean; });
+ addTranslations(locale: string, domain: string, translations: object): void;
+ dgettext(domain: string, msgid: string): string;
+ dngettext(domain: string, msgid: string, msgidPlural: string, count: number): string;
+ dnpgettext(domain: string, msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
+ dpgettext(domain: string, msgctxt: string, msgid: string): string;
+ emit(eventName: string, eventData: any): void;
+ getComment(domain: string, msgctxt: string, msgid: string): object | boolean;
+ gettext(msgid: string): string;
+ ngettext(msgid: string, msgidPlural: string, count: number): string;
+ npgettext(msgctxt: string, msgid: string, msgidPlural: string, count: number): string;
+ off(eventName: string, callback: (params: any) => void): string;
+ on(eventName: string, callback: (params: any) => void): void;
+ pgettext(msgctxt: string, msgid: string): string;
+ setLocale(locale: string): void;
+ setTextDomain(domain: string): void;
+ static getLanguageCode(locale: string): string;
+ textdomain(domain: string): void;
+ warn(message: string): void;
+}
diff --git a/node-gettext/node-gettext-tests.ts b/node-gettext/node-gettext-tests.ts
new file mode 100644
index 0000000000..e20e6aacac
--- /dev/null
+++ b/node-gettext/node-gettext-tests.ts
@@ -0,0 +1,34 @@
+// with tsc v 2.7 & esModuleInterop & allowSyntheticDefaultImports enabled in tsconfig.json
+import Gettext from 'node-gettext';
+// or without
+// import Gettext = require('node-getttext');
+
+const translations = {};
+const gt = new Gettext({ debug: true });
+const msgid = 'Get translation';
+const msgidPlural = 'Get translations';
+const domain = 'domain';
+const msgctxt = 'context';
+const count = 2;
+
+gt.addTranslations('en-US', 'messages', translations);
+gt.setTextDomain(domain);
+gt.textdomain(domain);
+gt.setLocale('en-US');
+gt.gettext(msgid);
+gt.dgettext('', msgid);
+gt.dngettext(domain, msgid, msgidPlural, count);
+gt.dnpgettext(domain, msgctxt, msgid, msgidPlural, count);
+gt.dpgettext(domain, msgctxt, msgid);
+gt.getComment(domain, msgctxt, msgid);
+gt.ngettext(msgid, msgidPlural, count);
+gt.npgettext(msgctxt, msgid, msgidPlural, count);
+gt.pgettext(msgctxt, msgid);
+Gettext.getLanguageCode('en-US');
+gt.warn('warning');
+const errorListener = (error: string) => {
+ // do something;
+};
+gt.on('error', errorListener);
+gt.emit('error', 'Error occurred');
+gt.off('error', errorListener);
diff --git a/node-gettext/tsconfig.json b/node-gettext/tsconfig.json
new file mode 100644
index 0000000000..9306d23426
--- /dev/null
+++ b/node-gettext/tsconfig.json
@@ -0,0 +1,24 @@
+{
+ "compilerOptions": {
+ "module": "commonjs",
+ "lib": [
+ "es6"
+ ],
+ "noImplicitAny": true,
+ "noImplicitThis": true,
+ "strictNullChecks": true,
+ "baseUrl": "../",
+ "typeRoots": [
+ "../"
+ ],
+ "types": [],
+ "noEmit": true,
+ "forceConsistentCasingInFileNames": true,
+ "esModuleInterop": true,
+ "allowSyntheticDefaultImports": true
+ },
+ "files": [
+ "index.d.ts",
+ "node-gettext-tests.ts"
+ ]
+}
diff --git a/types/hibp/tslint.json b/node-gettext/tslint.json
similarity index 100%
rename from types/hibp/tslint.json
rename to node-gettext/tslint.json
diff --git a/notNeededPackages.json b/notNeededPackages.json
index 251442309d..4acd790e24 100644
--- a/notNeededPackages.json
+++ b/notNeededPackages.json
@@ -684,6 +684,12 @@
"sourceRepoURL": "https://handsontable.com/",
"asOfVersion": "0.35.0"
},
+ {
+ "libraryName": "hibp",
+ "typingsPackageName": "hibp",
+ "sourceRepoURL": "https://github.com/wKovacs64/hibp",
+ "asOfVersion": "7.3.0"
+ },
{
"libraryName": "homeworks",
"typingsPackageName": "homeworks",
@@ -1482,6 +1488,12 @@
"sourceRepoURL": "https://github.com/zeh/simplesignal",
"asOfVersion": "1.0.0"
},
+ {
+ "libraryName": "sip.js",
+ "typingsPackageName": "sip.js",
+ "sourceRepoURL": "https://github.com/onsip/SIP.js",
+ "asOfVersion": "0.12.0"
+ },
{
"libraryName": "smooth-scrollbar",
"typingsPackageName": "smooth-scrollbar",
diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts
index cd20b57f05..2588539c0c 100644
--- a/types/ace/index.d.ts
+++ b/types/ace/index.d.ts
@@ -549,6 +549,16 @@ declare namespace AceAjax {
getFoldsInRange(range: Range): any;
highlight(text: string): void;
+
+
+ /**
+ * Highlight lines from `startRow` to `EndRow`.
+ * @param startRow Define the start line of the highlight
+ * @param endRow Define the end line of the highlight
+ * @param clazz Set the CSS class for the marker
+ * @param inFront Set to `true` to establish a front marker
+ **/
+ highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range;
/**
* Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`.
diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts
index 13f7f56ff9..e4f9e09e7c 100644
--- a/types/ali-oss/index.d.ts
+++ b/types/ali-oss/index.d.ts
@@ -18,6 +18,7 @@ declare namespace OSS {
internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money.
secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol.
timeout?: string | number; // instance level timeout for all operations, default is 60s
+ cname?: boolean; // use custom domain name
}
interface Bucket {
@@ -29,7 +30,7 @@ declare namespace OSS {
type StorageType = "Standard" | "IA" | "Archive";
- type ACLType = "public-read-write" | "public-read" | "and private";
+ type ACLType = "public-read-write" | "public-read" | "private";
type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT";
@@ -174,6 +175,7 @@ declare namespace OSS {
mime?: string; // custom mime, will send with Content-Type entity header
meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 }
callback: ObjectCallback;
+ headers?: object;
}
interface PutObjectResult {
@@ -188,6 +190,7 @@ declare namespace OSS {
mime: string; // custom mime, will send with Content-Type entity header
meta: UserMeta;
callback: ObjectCallback;
+ headers?: object;
}
interface AppendObjectOptions {
diff --git a/types/autobahn/autobahn-tests.ts b/types/autobahn/autobahn-tests.ts
index d753e960fe..8f05c25141 100644
--- a/types/autobahn/autobahn-tests.ts
+++ b/types/autobahn/autobahn-tests.ts
@@ -43,5 +43,7 @@ function test_client() {
});
};
- connection.open();
+ if (!connection.isOpen && !connection.isRetrying && connection.session == null) {
+ connection.open();
+ }
}
diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts
index c62f6115af..7a518e0fd4 100644
--- a/types/autobahn/index.d.ts
+++ b/types/autobahn/index.d.ts
@@ -1,6 +1,6 @@
-// Type definitions for AutobahnJS v0.9.7
+// Type definitions for AutobahnJS 0.9
// Project: http://autobahn.ws/js/
-// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier
+// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino , Mathias Teier
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
///
@@ -191,7 +191,9 @@ declare namespace autobahn {
constructor(options?: IConnectionOptions);
isOpen: boolean;
-
+ isRetrying: boolean;
+ session?: Session;
+
open(): void;
close(reason?: string, message?: string): void;
diff --git a/types/autobahn/tslint.json b/types/autobahn/tslint.json
index a41bf5d19a..a0357daa61 100644
--- a/types/autobahn/tslint.json
+++ b/types/autobahn/tslint.json
@@ -7,7 +7,6 @@
"ban-types": false,
"callable-types": false,
"comment-format": false,
- "dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
diff --git a/types/boxen/boxen-tests.ts b/types/boxen/boxen-tests.ts
new file mode 100644
index 0000000000..303e5dd7fa
--- /dev/null
+++ b/types/boxen/boxen-tests.ts
@@ -0,0 +1,37 @@
+import boxen = require('boxen');
+
+boxen('unicorn'); // $ExpectType string
+boxen('unicorn', { borderColor: 'black' }); // $ExpectType string
+boxen('unicorn', { borderStyle: 'double' }); // $ExpectType string
+boxen('unicorn', { borderStyle: 'foo' }); // $ExpectError
+// $ExpectType string
+boxen('unicorn', {
+ borderStyle: {
+ topLeft: '+',
+ topRight: '+',
+ bottomLeft: '+',
+ bottomRight: '+',
+ horizontal: '-',
+ vertical: '|',
+ },
+});
+boxen('unicorn', { dimBorder: true }); // $ExpectType string
+boxen('unicorn', { padding: 1 }); // $ExpectType string
+boxen('unicorn', { padding: { top: 1 } }); // $ExpectType string
+boxen('unicorn', { padding: { right: 1 } }); // $ExpectType string
+boxen('unicorn', { padding: { bottom: 1 } }); // $ExpectType string
+boxen('unicorn', { padding: { left: 1 } }); // $ExpectType string
+boxen('unicorn', { margin: 1 }); // $ExpectType string
+boxen('unicorn', { margin: { top: 1 } }); // $ExpectType string
+boxen('unicorn', { margin: { right: 1 } }); // $ExpectType string
+boxen('unicorn', { margin: { bottom: 1 } }); // $ExpectType string
+boxen('unicorn', { margin: { left: 1 } }); // $ExpectType string
+boxen('unicorn', { float: 'right' }); // $ExpectType string
+boxen('unicorn', { float: 'center' }); // $ExpectType string
+boxen('unicorn', { float: 'left' }); // $ExpectType string
+boxen('unicorn', { float: 'foo' }); // $ExpectError
+boxen('unicorn', { backgroundColor: 'white' }); // $ExpectType string
+boxen('unicorn', { align: 'left' }); // $ExpectType string
+boxen('unicorn', { align: 'center' }); // $ExpectType string
+boxen('unicorn', { align: 'right' }); // $ExpectType string
+boxen('unicorn', { align: 'foo' }); // $ExpectError
diff --git a/types/boxen/index.d.ts b/types/boxen/index.d.ts
new file mode 100644
index 0000000000..94b68bb5c7
--- /dev/null
+++ b/types/boxen/index.d.ts
@@ -0,0 +1,114 @@
+// Type definitions for boxen 2.1
+// Project: https://github.com/sindresorhus/boxen#readme
+// Definitions by: BendingBender
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+// TypeScript Version: 2.1
+
+import { BoxDefinition, BoxNames } from 'cli-boxes';
+
+export = boxen;
+
+/**
+ * Create boxes in the terminal
+ * @param input Text inside the box.
+ */
+declare function boxen(input: string, options?: boxen.Options): string;
+
+declare namespace boxen {
+ interface Options {
+ /**
+ * Color of the box border.
+ * Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000`
+ */
+ borderColor?: string;
+
+ /**
+ * Style of the box border.
+ * Can be any of the above predefined styles or an object.
+ *
+ * Predefined values:
+ * - `single`
+ * ```
+ * ┌───┐
+ * │foo│
+ * └───┘
+ * ```
+ * - `double`
+ * ```
+ * ╔═══╗
+ * ║foo║
+ * ╚═══╝
+ * ```
+ * - `round` (`single` sides with round corners)
+ * ```
+ * ╭───╮
+ * │foo│
+ * ╰───╯
+ * ```
+ * - `single-double` (`single` on top and bottom, `double` on right and left)
+ * ```
+ * ╓───╖
+ * ║foo║
+ * ╙───╜
+ * ```
+ * - `double-single` (`double` on top and bottom, `single` on right and left)
+ * ```
+ * ╒═══╕
+ * │foo│
+ * ╘═══╛
+ * ```
+ * - `classic`
+ * ```
+ * +---+
+ * |foo|
+ * +---+
+ * ```
+ */
+ borderStyle?: BoxNames | BoxDefinition;
+
+ /**
+ * Reduce opacity of the border.
+ * @default false
+ */
+ dimBorder?: boolean;
+
+ /**
+ * Space between the text and box border.
+ * When a number is specified, the left/right padding is 3 times the top/bottom to make it look nice.
+ * @default 0
+ */
+ padding?: number | PositionOptions;
+
+ /**
+ * Space around the box.
+ * When a number is specified, the left/right margin is 3 times the top/bottom to make it look nice.
+ * @default 0
+ */
+ margin?: number | PositionOptions;
+
+ /**
+ * Float the box on the available terminal screen space.
+ * @default 'left'
+ */
+ float?: 'right' | 'center' | 'left';
+
+ /**
+ * Color of the background.
+ * Values: `black` `red` `green` `yellow` `blue` `magenta` `cyan` `white` `gray` or a hex value like `#ff0000`
+ */
+ backgroundColor?: string;
+
+ /**
+ * Align the text in the box based on the widest line.
+ * @default 'left'
+ */
+ align?: 'left' | 'center' | 'right';
+ }
+
+ interface PositionOptions {
+ top?: number;
+ right?: number;
+ bottom?: number;
+ left?: number;
+ }
+}
diff --git a/types/boxen/tsconfig.json b/types/boxen/tsconfig.json
new file mode 100644
index 0000000000..6d34147e83
--- /dev/null
+++ b/types/boxen/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",
+ "boxen-tests.ts"
+ ]
+}
diff --git a/types/boxen/tslint.json b/types/boxen/tslint.json
new file mode 100644
index 0000000000..3db14f85ea
--- /dev/null
+++ b/types/boxen/tslint.json
@@ -0,0 +1 @@
+{ "extends": "dtslint/dt.json" }
diff --git a/types/bytebuffer/index.d.ts b/types/bytebuffer/index.d.ts
index 4423d7872b..bafed6edf8 100644
--- a/types/bytebuffer/index.d.ts
+++ b/types/bytebuffer/index.d.ts
@@ -146,7 +146,7 @@ declare class ByteBuffer
/**
* Concatenates multiple ByteBuffers into one.
*/
- static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer;
+ static concat( buffers: Array, encoding?: string | boolean, litteEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a base64 encoded string to a ByteBuffer.
@@ -185,7 +185,7 @@ declare class ByteBuffer
* @param littleEndian Whether to use little or big endian byte order. Defaults to ByteBuffer.DEFAULT_ENDIAN.
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteBuffer.DEFAULT_NOASSERT.
*/
- static wrap( buffer: ByteBuffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
+ static wrap( buffer: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, enc?: string | boolean, littleEndian?: boolean, noAssert?: boolean ): ByteBuffer;
/**
* Decodes a zigzag encoded signed 32bit integer.
@@ -220,7 +220,7 @@ declare class ByteBuffer
/**
* Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended data's length.
*/
- append( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
+ append( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents behind the specified offset up to the length of this ByteBuffer's data.
@@ -291,7 +291,7 @@ declare class ByteBuffer
/**
* Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
*/
- prepend( source: ByteBuffer | string | ArrayBuffer, encoding?: string | number, offset?: number ): ByteBuffer;
+ prepend( source: ByteBuffer | string | ArrayBuffer | Buffer, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the prepended data's length. If there is not enough space available before the specified offset, the backing buffer will be resized and its contents moved accordingly.
@@ -480,7 +480,7 @@ declare class ByteBuffer
/**
* Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between ByteBuffer#offset and ByteBuffer#limit. Will transparently ByteBuffer#flip this ByteBuffer if offset > limit but the actual offsets remain untouched.
*/
- toBuffer( forceCopy?: boolean ): ArrayBuffer;
+ toBuffer( forceCopy?: boolean ): Buffer;
/**
*Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
@@ -517,7 +517,7 @@ declare class ByteBuffer
/**
* Writes an array of bytes. This is an alias for append
*/
- writeBytes( source: ByteBuffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
+ writeBytes( source: ByteBuffer | Buffer | ArrayBuffer | Uint8Array | string, encoding?: string | number, offset?: number ): ByteBuffer;
/**
* Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL characters itself.
diff --git a/types/classnames/bind.d.ts b/types/classnames/bind.d.ts
index 4af94d1835..9befbabd4c 100644
--- a/types/classnames/bind.d.ts
+++ b/types/classnames/bind.d.ts
@@ -1,3 +1,3 @@
-import * as cn from "./index";
+import classNames = require('./index');
-export function bind(styles: Record): typeof cn;
+export function bind(styles: Record): typeof classNames;
diff --git a/types/classnames/tsconfig.json b/types/classnames/tsconfig.json
index f9b03432fc..0e8475e613 100644
--- a/types/classnames/tsconfig.json
+++ b/types/classnames/tsconfig.json
@@ -6,7 +6,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
- "strictNullChecks": false,
+ "strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
diff --git a/types/cordova-plugin-x-socialsharing/index.d.ts b/types/cordova-plugin-x-socialsharing/index.d.ts
index a5105c898c..d1a4740b58 100644
--- a/types/cordova-plugin-x-socialsharing/index.d.ts
+++ b/types/cordova-plugin-x-socialsharing/index.d.ts
@@ -1,13 +1,13 @@
-// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.8
+// Type definitions for SocialSharing-PhoneGap-Plugin v5.1.9
// Project: https://github.com/EddyVerbruggen/SocialSharing-PhoneGap-Plugin
// Definitions by: Markus Wagner , Larry Bahr
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface Window {
- plugins: Plugins;
+ plugins: CordovaPlugins;
}
-interface Plugins {
+interface CordovaPlugins {
socialsharing: SocialSharingPlugin.SocialSharing;
}
diff --git a/types/d3-cloud/d3-cloud-tests.ts b/types/d3-cloud/d3-cloud-tests.ts
index 862b7f0d82..e3bffed4cb 100644
--- a/types/d3-cloud/d3-cloud-tests.ts
+++ b/types/d3-cloud/d3-cloud-tests.ts
@@ -1,3 +1,12 @@
+import d3Cloud = require('./index.d');
+import d3 = require('d3');
+
+// $ExpectType Cloud
+d3Cloud();
+
+// $ExpectType Cloud
+d3.layout.cloud();
+
interface ICompTextSize{
text:string;
size:number;
diff --git a/types/d3-cloud/index.d.ts b/types/d3-cloud/index.d.ts
index 70e2140bd5..fdf2dbc719 100644
--- a/types/d3-cloud/index.d.ts
+++ b/types/d3-cloud/index.d.ts
@@ -5,6 +5,8 @@
import * as d3 from 'd3';
+export = d3.layout.cloud;
+
declare module 'd3' {
namespace layout {
export function cloud(): Cloud;
diff --git a/types/d3-dsv/d3-dsv-tests.ts b/types/d3-dsv/d3-dsv-tests.ts
index 259180632f..8e05b04e61 100644
--- a/types/d3-dsv/d3-dsv-tests.ts
+++ b/types/d3-dsv/d3-dsv-tests.ts
@@ -21,6 +21,9 @@ const csvTestStringWithHeader = `Year,Make,Model,Length\n${csvTestString}`;
const tsvTestStringWithHeader = `Year\tMake\tModel\tLength\n${tsvTestString}`;
const pipedTestStringWithHeader = `Year|Make|Model|Length\n${pipedTestString}`;
+type Headers = "Year" | "Make" | "Model" | "Length";
+type ParsedHeaders = "year" | "make" | "model" | "length";
+
interface ParsedTestObject {
year: Date | null;
make: string;
@@ -28,17 +31,56 @@ interface ParsedTestObject {
length: number;
}
-let parseArray: d3Dsv.DSVParsedArray;
-let parseMappedArray: d3Dsv.DSVParsedArray;
-
let parseRowsArray: string[][];
let parseRowsMappedArray: ParsedTestObject[];
-
let parsedTestObject: ParsedTestObject;
-let columns: string[];
+
+let num: number;
let str: string;
let strMaybe: string | undefined;
+let columns: string[];
+let headers: Headers[];
+let parsedHeaders: ParsedHeaders[];
+
+// ------------------------------------------------------------------------------------------
+// Test Shared Types and Interfaces
+// ------------------------------------------------------------------------------------------
+
+declare let row: d3Dsv.DSVRowString;
+strMaybe = row.property;
+
+declare let row2: d3Dsv.DSVRowString;
+strMaybe = row2.Make;
+strMaybe = row2.Property; // $ExpectError
+
+declare let raw: d3Dsv.DSVRaw;
+strMaybe = raw.make;
+strMaybe = raw.property; // $ExpectError
+
+declare let rowArray: d3Dsv.DSVRowArray;
+strMaybe = rowArray[0].property;
+columns = rowArray.columns;
+num = rowArray.length;
+
+declare let rowArrayHeader: d3Dsv.DSVRowArray;
+strMaybe = rowArrayHeader[0].Make;
+strMaybe = rowArrayHeader[0].Property; // $ExpectError
+headers = rowArrayHeader.columns;
+num = rowArrayHeader.length;
+
+declare let parseMappedArray: d3Dsv.DSVParsedArray;
+strMaybe = parseMappedArray[0].make;
+strMaybe = parseMappedArray[0].property; // $ExpectError
+parsedTestObject = parseMappedArray[0];
+parsedHeaders = parseMappedArray.columns;
+num = parseMappedArray.length;
+
+declare let parseArray: d3Dsv.DSVParsedArray;
+strMaybe = parseArray[0].property;
+columns = parseArray.columns;
+num = parseArray.length;
+
// ------------------------------------------------------------------------------------------
// Test CSV
// ------------------------------------------------------------------------------------------
@@ -48,8 +90,7 @@ let strMaybe: string | undefined;
// without row mapper -----------------------------------------------------------------------
parseArray = d3Dsv.csvParse(csvTestStringWithHeader);
-columns = parseArray.columns;
-strMaybe = parseArray[0].Year;
+rowArrayHeader = d3Dsv.csvParse(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -73,8 +114,12 @@ parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, colum
return pr;
});
-columns = parseMappedArray.columns;
-parsedTestObject = parseMappedArray[0];
+parseMappedArray = d3Dsv.csvParse(csvTestStringWithHeader, (rawRow, index, columns) => {
+ const rr: d3Dsv.DSVRowString = rawRow;
+ const i: number = index;
+ const c: Headers[] = columns;
+ return parsedTestObject;
+});
// csvParseRows(...) ============================================================================
@@ -108,12 +153,11 @@ parseRowsMappedArray = d3Dsv.csvParseRows(csvTestString, (rawRow, index) => {
str = d3Dsv.csvFormat(parseRowsMappedArray);
str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "length"]);
-// $ExpectError
-str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]);
+str = d3Dsv.csvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// csvFormatRows(...) ========================================================================
-str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [
+str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
@@ -129,8 +173,7 @@ str = d3Dsv.csvFormatRows(parseRowsMappedArray.map((d, i) => [
// without row mapper -----------------------------------------------------------------------
parseArray = d3Dsv.tsvParse(tsvTestStringWithHeader);
-columns = parseArray.columns;
-strMaybe = parseArray[0].Year;
+rowArrayHeader = d3Dsv.tsvParse(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -154,8 +197,12 @@ parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, colum
return pr;
});
-columns = parseMappedArray.columns;
-parsedTestObject = parseMappedArray[0];
+parseMappedArray = d3Dsv.tsvParse(tsvTestStringWithHeader, (rawRow, index, columns) => {
+ const rr: d3Dsv.DSVRowString = rawRow;
+ const i: number = index;
+ const c: Headers[] = columns;
+ return parsedTestObject;
+});
// tsvParseRows(...) ============================================================================
@@ -189,12 +236,11 @@ parseRowsMappedArray = d3Dsv.tsvParseRows(tsvTestString, (rawRow, index) => {
str = d3Dsv.tsvFormat(parseRowsMappedArray);
str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "length"]);
-// $ExpectError
-str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]);
+str = d3Dsv.tsvFormat(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// tsvFormatRows(...) ========================================================================
-str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d, i) => [
+str = d3Dsv.tsvFormatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
@@ -215,8 +261,7 @@ dsv = d3Dsv.dsvFormat('|');
// without row mapper -----------------------------------------------------------------------
parseArray = dsv.parse(pipedTestStringWithHeader);
-columns = parseArray.columns;
-strMaybe = parseArray[0].Year;
+rowArrayHeader = dsv.parse(csvTestStringWithHeader);
// with row mapper ---------------------------------------------------------------------------
@@ -240,8 +285,12 @@ parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns)
return pr;
});
-columns = parseMappedArray.columns;
-parsedTestObject = parseMappedArray[0];
+parseMappedArray = dsv.parse(pipedTestStringWithHeader, (rawRow, index, columns) => {
+ const rr: d3Dsv.DSVRowString = rawRow;
+ const i: number = index;
+ const c: Headers[] = columns;
+ return parsedTestObject;
+});
// parseRows(...) ============================================================================
@@ -275,12 +324,11 @@ parseRowsMappedArray = dsv.parseRows(pipedTestString, (rawRow, index) => {
str = dsv.format(parseRowsMappedArray);
str = dsv.format(parseRowsMappedArray, ["year", "length"]);
-// $ExpectError
-str = dsv.format(parseRowsMappedArray, ["year", "unknown"]);
+str = dsv.format(parseRowsMappedArray, ["year", "unknown"]); // $ExpectError
// formatRows(...) ========================================================================
-str = dsv.formatRows(parseRowsMappedArray.map((d, i) => [
+str = dsv.formatRows(parseRowsMappedArray.map((d) => [
d.year ? d.year.getFullYear().toString() : '',
d.make,
d.model,
diff --git a/types/d3-dsv/index.d.ts b/types/d3-dsv/index.d.ts
index bdebc5ca01..fcfaa67339 100644
--- a/types/d3-dsv/index.d.ts
+++ b/types/d3-dsv/index.d.ts
@@ -15,21 +15,41 @@
/**
* An object representing a DSV parsed row with values represented as strings.
+ * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value.
*/
-export interface DSVRowString {
- [key: string]: string | undefined;
-}
+export type DSVRowString = {
+ [key in Columns]: string | undefined;
+};
+
+/**
+ * An object in raw format before parsing, that is with only string values.
+ * When the DSV content is not well-structured and some column-values are missing, `undefined` is used as value.
+ */
+export type DSVRaw = {
+ [key in keyof T]: string | undefined;
+};
/**
* An object representing a DSV parsed row with values represented as an arbitrary datatype, depending
* on the performed parsed row mapping.
*
- * @deprecated
+ * @deprecated Use `object` instead.
*/
export interface DSVRowAny {
[key: string]: any;
}
+/**
+ * An array object representing all deserialized rows. The array is enhanced with a property listing
+ * the names of the parsed columns.
+ */
+export interface DSVRowArray extends Array> {
+ /**
+ * List of column names.
+ */
+ columns: Columns[];
+}
+
/**
* An array object representing all parsed rows. The array is enhanced with a property listing
* the names of the parsed columns.
@@ -38,7 +58,7 @@ export interface DSVParsedArray extends Array {
/**
* List of column names.
*/
- columns: string[];
+ columns: Array;
}
// ------------------------------------------------------------------------------------------
@@ -55,11 +75,12 @@ export interface DSVParsedArray extends Array {
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
- * Equivalent to dsvFormat(",").parse.
+ * Equivalent to `dsvFormat(",").parse`.
*
* @param csvString A string, which must be in the comma-separated values format.
*/
-export function csvParse(csvString: string): DSVParsedArray;
+// tslint:disable-next-line:no-unnecessary-generics
+export function csvParse(csvString: string): DSVRowArray;
/**
* Parses the specified string, which must be in the comma-separated values format, returning an array of objects representing the parsed rows.
*
@@ -68,7 +89,7 @@ export function csvParse(csvString: string): DSVParsedArray;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
- * Equivalent to dsvFormat(",").parse.
+ * Equivalent to `dsvFormat(",").parse`.
*
* @param csvString A string, which must be in the comma-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -76,9 +97,9 @@ export function csvParse(csvString: string): DSVParsedArray;
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function csvParse(
+export function csvParse(
csvString: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): DSVParsedArray;
// csvParseRows(...) ========================================================================
@@ -92,7 +113,7 @@ export function csvParse(
* If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types.
* In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function.
*
- * Equivalent to dsvFormat(",").parseRows.
+ * Equivalent to `dsvFormat(",").parseRows`.
*
* @param csvString A string, which must be in the comma-separated values format.
*/
@@ -103,7 +124,7 @@ export function csvParseRows(csvString: string): string[][];
* Unlike csvParse, this method treats the header line as a standard row, and should be used whenever CSV content does not contain a header.
* Each row is represented as an array rather than an object. Rows may have variable length.
*
- * Equivalent to dsvFormat(",").parseRows.
+ * Equivalent to `dsvFormat(",").parseRows`.
*
* @param csvString A string, which must be in the comma-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i)
@@ -127,7 +148,7 @@ export function csvParseRows(
* If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows;
* the order of columns is nondeterministic.
*
- * Equivalent to dsvFormat(",").format.
+ * Equivalent to `dsvFormat(",").format`.
*
* @param rows Array of object rows.
* @param columns An array of strings representing the column names.
@@ -145,7 +166,7 @@ export function csvFormat(rows: T[], columns?: Array)
* To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map.
* If you like, you can also array.concat this result with an array of column names to generate the first row.
*
- * Equivalent to dsvFormat(",").formatRows.
+ * Equivalent to `dsvFormat(",").formatRows`.
*
* @param rows An array of array of string rows.
*/
@@ -165,11 +186,12 @@ export function csvFormatRows(rows: string[][]): string;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
- * Equivalent to dsvFormat("\t").parse.
+ * Equivalent to `dsvFormat("\t").parse`.
*
* @param tsvString A string, which must be in the tab-separated values format.
*/
-export function tsvParse(tsvString: string): DSVParsedArray;
+// tslint:disable-next-line:no-unnecessary-generics
+export function tsvParse(tsvString: string): DSVRowArray;
/**
* Parses the specified string, which must be in the tab-separated values format, returning an array of objects representing the parsed rows.
*
@@ -178,7 +200,7 @@ export function tsvParse(tsvString: string): DSVParsedArray;
*
* The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).
*
- * Equivalent to dsvFormat("\t").parse.
+ * Equivalent to `dsvFormat("\t").parse`.
*
* @param tsvString A string, which must be in the tab-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -186,10 +208,10 @@ export function tsvParse(tsvString: string): DSVParsedArray;
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function tsvParse(
+export function tsvParse(
tsvString: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => MappedRow | undefined | null
-): DSVParsedArray;
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
+): DSVParsedArray;
// tsvParseRows(...) ========================================================================
@@ -202,7 +224,7 @@ export function tsvParse(
* If a row conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types.
* In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the + operator), but better is to specify a row conversion function.
*
- * Equivalent to dsvFormat("\t").parseRows.
+ * Equivalent to `dsvFormat("\t").parseRows`.
*
* @param tsvString A string, which must be in the tab-separated values format.
*/
@@ -213,7 +235,7 @@ export function tsvParseRows(tsvString: string): string[][];
* Unlike tsvParse, this method treats the header line as a standard row, and should be used whenever TSV content does not contain a header.
* Each row is represented as an array rather than an object. Rows may have variable length.
*
- * Equivalent to dsvFormat("\t").parseRows.
+ * Equivalent to `dsvFormat("\t").parseRows`.
*
* @param tsvString A string, which must be in the tab-separated values format.
* @param row A row conversion function which is invoked for each row, being passed an array representing the current row (d), the index (i)
@@ -221,10 +243,10 @@ export function tsvParseRows(tsvString: string): string[][];
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function tsvParseRows(
+export function tsvParseRows(
tsvString: string,
- row: (rawRow: string[], index: number) => MappedRow | undefined | null
-): MappedRow[];
+ row: (rawRow: string[], index: number) => ParsedRow | undefined | null
+): ParsedRow[];
// tsvFormat(...) ============================================================================
@@ -237,7 +259,7 @@ export function tsvParseRows(
* If columns is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in rows;
* the order of columns is nondeterministic.
*
- * Equivalent to dsvFormat("\t").format.
+ * Equivalent to `dsvFormat("\t").format`.
*
* @param rows Array of object rows.
* @param columns An array of strings representing the column names.
@@ -255,7 +277,7 @@ export function tsvFormat(rows: T[], columns?: Array)
* To convert an array of objects to an array of arrays while explicitly specifying the columns, use array.map.
* If you like, you can also array.concat this result with an array of column names to generate the first row.
*
- * Equivalent to dsvFormat("\t").formatRows.
+ * Equivalent to `dsvFormat("\t").formatRows`.
*
* @param rows An array of array of string rows.
*/
@@ -279,7 +301,8 @@ export interface DSV {
*
* @param dsvString A string, which must be in the delimiter-separated values format with the appropriate delimiter.
*/
- parse(dsvString: string): DSVParsedArray;
+ // tslint:disable-next-line:no-unnecessary-generics
+ parse(dsvString: string): DSVRowArray;
/**
* Parses the specified string, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.
*
@@ -294,9 +317,9 @@ export interface DSV {
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
- parse(
+ parse(
dsvString: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): DSVParsedArray;
/**
diff --git a/types/d3-fetch/d3-fetch-tests.ts b/types/d3-fetch/d3-fetch-tests.ts
index 4d49d86a7f..8d6b862afc 100644
--- a/types/d3-fetch/d3-fetch-tests.ts
+++ b/types/d3-fetch/d3-fetch-tests.ts
@@ -1,62 +1,158 @@
import * as d3Fetch from 'd3-fetch';
-import { DSVParsedArray, DSVRowString } from 'd3-dsv';
+import { DSVParsedArray, DSVRaw, DSVRowString } from 'd3-dsv';
-interface MyType {
- foo: string;
+// ----------------------------------------------------------------------------
+// Preparatory Steps
+// ----------------------------------------------------------------------------
+
+type Headers = "Year" | "Make" | "Model" | "Length";
+
+interface Car {
+ year: Date;
+ make: string;
+ model: string;
+ length: number;
}
-const url = 'foo.bar';
-
-const init: RequestInit = {};
-
-let p1: Promise = d3Fetch.blob(url);
-p1 = d3Fetch.blob(url, init);
-
-let p2: Promise = d3Fetch.buffer(url);
-p2 = d3Fetch.buffer(url, init);
-
-let p3: Promise = d3Fetch.image(url);
-const imageProperties = {
- width: '300px',
- height: '500px'
-};
-p3 = d3Fetch.image(url, imageProperties);
-
-let p4: Promise = d3Fetch.json(url);
-p4 = d3Fetch.json(url, init);
-let p5: Promise = d3Fetch.json(url);
-p5 = d3Fetch.json(url, init);
-
-let myString: Promise;
-myString = d3Fetch.text(url);
-myString = d3Fetch.text(url, init);
-
-const parseRow = (rawRow: DSVRowString, index: number, columns: string[]): (MyType | undefined | null) => {
- const myType: MyType | null = rawRow['foo'] ? { foo: rawRow['foo'] + '+ bar' } : null;
- return myType;
-};
-let promise1: Promise>;
-let promise2: Promise>;
-promise1 = d3Fetch.csv(url);
-promise1 = d3Fetch.csv(url, init);
-promise2 = d3Fetch.csv(url, parseRow);
-promise2 = d3Fetch.csv(url, init, parseRow);
-promise1 = d3Fetch.dsv(';', url);
-promise1 = d3Fetch.dsv(';', url, init);
-promise2 = d3Fetch.dsv(';', url, parseRow);
-promise2 = d3Fetch.dsv(';', url, init, parseRow);
-promise1 = d3Fetch.tsv(url);
-promise1 = d3Fetch.tsv(url, init);
-promise2 = d3Fetch.tsv(url, parseRow);
-promise2 = d3Fetch.tsv(url, init, parseRow);
-
+let anyPromise: Promise;
+let arrayPromise: Promise;
+let blobPromise: Promise;
let docPromise: Promise;
+let imagePromise: Promise;
+let carPromise: Promise;
+let stringPromise: Promise;
+let xmlDocPromise: Promise;
+
+const url = 'example.org';
+const init: RequestInit = {};
+const map = new Map();
+
+const imageProperties = {
+ width: 300,
+ height: 500,
+ crossOrigin: "anonymous",
+};
+
+// ----------------------------------------------------------------------------
+// Non DSV file format
+// ----------------------------------------------------------------------------
+
+blobPromise = d3Fetch.blob(url);
+blobPromise = d3Fetch.blob(url, init);
+
+arrayPromise = d3Fetch.buffer(url);
+arrayPromise = d3Fetch.buffer(url, init);
+
+imagePromise = d3Fetch.image(url);
+imagePromise = d3Fetch.image(url, imageProperties);
+// $ExpectError
+imagePromise = d3Fetch.image(url, {width: "500px"}); // fails, string not assignable to number | undefined
+
+anyPromise = d3Fetch.json(url);
+anyPromise = d3Fetch.json(url, init);
+
+carPromise = d3Fetch.json(url);
+carPromise = d3Fetch.json(url, init);
+
+stringPromise = d3Fetch.text(url);
+stringPromise = d3Fetch.text(url, init);
+
docPromise = d3Fetch.html(url);
docPromise = d3Fetch.html(url, init);
docPromise = d3Fetch.svg(url);
docPromise = d3Fetch.svg(url, init);
-let xmlDocPromise: Promise;
xmlDocPromise = d3Fetch.xml(url);
xmlDocPromise = d3Fetch.xml(url, init);
+
+// ----------------------------------------------------------------------------
+// DSV file format
+// ----------------------------------------------------------------------------
+
+let rawPromise: Promise>;
+let rawPromiseHeader: Promise>>;
+let parsedPromise: Promise>;
+
+declare const parseRowString: (rawRow: DSVRowString, index: number, columns: string[]) => Car | undefined | null;
+
+const parseRow = (d: DSVRowString, index: number, columns: Headers[]): Car | undefined | null => {
+ const item: string | undefined = d[columns[0]];
+ const car = d.Make === 'Ford' ? null :
+ {
+ year: new Date(+d.Make!, 0, 1),
+ make: d.Make!,
+ model: d.Model!,
+ length: +d.Length!,
+ };
+ return index % 2 === 0 ? undefined : car;
+};
+
+const parseRowSimple = (d: DSVRaw) => {
+ return {
+ year: new Date(+d.make!, 0, 1),
+ make: d.make!,
+ model: d.model!,
+ length: +d.length!,
+ };
+};
+
+// CSV
+
+rawPromise = d3Fetch.csv(url);
+rawPromise = d3Fetch.csv(url, init);
+
+rawPromiseHeader = d3Fetch.csv(url);
+rawPromiseHeader = d3Fetch.csv(url, init);
+
+parsedPromise = d3Fetch.csv(url, parseRowString);
+parsedPromise = d3Fetch.csv(url, init, parseRowString);
+
+parsedPromise = d3Fetch.csv(url, parseRow);
+parsedPromise = d3Fetch.csv(url, init, parseRow);
+
+parsedPromise = d3Fetch.csv(url, parseRow);
+parsedPromise = d3Fetch.csv(url, init, parseRow);
+parsedPromise = d3Fetch.csv(url, parseRowSimple);
+
+anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!));
+
+// DSV
+
+rawPromise = d3Fetch.dsv("|", url);
+rawPromise = d3Fetch.dsv("|", url, init);
+
+rawPromiseHeader = d3Fetch.dsv("|", url);
+rawPromiseHeader = d3Fetch.dsv("|", url, init);
+
+parsedPromise = d3Fetch.dsv("|", url, parseRowString);
+parsedPromise = d3Fetch.dsv("|", url, init, parseRowString);
+
+parsedPromise = d3Fetch.dsv("|", url, parseRow);
+parsedPromise = d3Fetch.dsv("|", url, init, parseRow);
+
+parsedPromise = d3Fetch.dsv("|", url, parseRow);
+parsedPromise = d3Fetch.dsv("|", url, init, parseRow);
+parsedPromise = d3Fetch.dsv("|", url, parseRowSimple);
+
+anyPromise = d3Fetch.dsv("|", url, (d: DSVRaw) => map.set(d.model!, +d.year!));
+
+// TSV
+
+rawPromise = d3Fetch.tsv(url);
+rawPromise = d3Fetch.tsv(url, init);
+
+rawPromiseHeader = d3Fetch.tsv(url);
+rawPromiseHeader = d3Fetch.tsv(url, init);
+
+parsedPromise = d3Fetch.tsv(url, parseRowString);
+parsedPromise = d3Fetch.tsv(url, init, parseRowString);
+
+parsedPromise = d3Fetch.tsv(url, parseRow);
+parsedPromise = d3Fetch.tsv(url, init, parseRow);
+
+parsedPromise = d3Fetch.tsv(url, parseRow);
+parsedPromise = d3Fetch.tsv(url, init, parseRow);
+parsedPromise = d3Fetch.tsv(url, parseRowSimple);
+
+anyPromise = d3Fetch.csv(url, (d: DSVRaw) => map.set(d.model!, +d.year!));
diff --git a/types/d3-fetch/index.d.ts b/types/d3-fetch/index.d.ts
index f6dc317784..4110ba4a7b 100644
--- a/types/d3-fetch/index.d.ts
+++ b/types/d3-fetch/index.d.ts
@@ -1,12 +1,13 @@
// Type definitions for d3-fetch 1.1
// Project: https://d3js.org/d3-fetch/
// Definitions by: Hugues Stefanski
+// denisname
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// Last module patch version validated against: 1.1.0
-import { DSVParsedArray, DSVRowString } from 'd3-dsv';
+import { DSVParsedArray, DSVRowArray, DSVRowString } from "d3-dsv";
/**
* Fetches the binary file at the specified input URL and returns it as a Promise of a Blob.
@@ -33,13 +34,15 @@ export function buffer(url: string, init?: RequestInit): Promise;
*
* If init is specified, it is passed along to the underlying call to fetch.
*
+ * The generic parameter describes the column names as a union of string literal types.
+ *
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
-export function csv(
+export function csv(
url: string,
- init?: RequestInit,
-): Promise>;
+ init?: RequestInit
+): Promise>;
/**
* Fetches the CSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
@@ -47,7 +50,8 @@ export function csv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -55,9 +59,9 @@ export function csv(
* the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function csv(
+export function csv(
url: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
* Fetches the CSV file at the specified input URL and returns
@@ -68,7 +72,8 @@ export function csv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.csvParse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An request initialization object.
@@ -77,10 +82,10 @@ export function csv(
* the row is skipped and will be omitted from the array returned by dsv.csvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function csv(
+export function csv(
url: string,
init: RequestInit,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
@@ -90,15 +95,17 @@ export function csv(
*
* If init is specified, it is passed along to the underlying call to fetch.
*
+ * The generic parameter describes the column names as a union of string literal types.
+ *
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
-export function dsv(
+export function dsv(
delimiter: string,
url: string,
- init?: RequestInit,
-): Promise>;
+ init?: RequestInit
+): Promise>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
* a promise of an array of objects representing the parsed rows.
@@ -106,7 +113,8 @@ export function dsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
@@ -115,10 +123,10 @@ export function dsv(
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function dsv(
+export function dsv(
delimiter: string,
url: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
* Fetches the DSV file with the specified delimiter character at the specified input URL and returns
@@ -129,7 +137,8 @@ export function dsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.parse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param delimiter The delimiter character used in the DSV file to be fetched.
* @param url A valid URL string.
@@ -139,11 +148,11 @@ export function dsv(
* the row is skipped and will be omitted from the array returned by dsv.parse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function dsv(
+export function dsv(
delimiter: string,
url: string,
init: RequestInit,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
@@ -164,7 +173,7 @@ export function html(url: string, init?: RequestInit): Promise;
* @param url A valid URL string.
* @param init An optional object of image properties to set.
*/
-export function image(url: string, init?: {[key: string]: any}): Promise;
+export function image(url: string, init?: Partial): Promise;
/**
* Fetches the json file at the specified input URL and returns it as a Promise of a parsed JSON object.
@@ -204,13 +213,15 @@ export function text(url: string, init?: RequestInit): Promise;
*
* If init is specified, it is passed along to the underlying call to fetch.
*
+ * The generic parameter describes the column names as a union of string literal types.
+ *
* @param url A valid URL string.
* @param init An optional request initialization object.
*/
-export function tsv(
+export function tsv(
url: string,
- init?: RequestInit,
-): Promise>;
+ init?: RequestInit
+): Promise>;
/**
* Fetches the TSV file at the specified input URL and returns
* a promise of an array of objects representing the parsed rows. The values of the properties of the parsed row
@@ -219,7 +230,8 @@ export function tsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param row A row conversion function which is invoked for each row, being passed an object representing the current row (d),
@@ -227,9 +239,9 @@ export function tsv(
* the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function tsv(
+export function tsv(
url: string,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
* Fetches the TSV file at the specified input URL and returns
@@ -240,7 +252,8 @@ export function tsv(
* The specified row conversion function is used to map and filter row objects to a more-specific representation;
* see dsv.tsvParse for details.
*
- * The generic parameter describes the type of the object representation of a parsed row.
+ * The first generic parameter describes the type of the object representation of a parsed row.
+ * The second generic parameter describes the column names as a union of string literal types.
*
* @param url A valid URL string.
* @param init An request initialization object.
@@ -249,10 +262,10 @@ export function tsv(
* the row is skipped and will be omitted from the array returned by dsv.tsvParse; otherwise, the returned value defines the corresponding row object.
* In effect, row is similar to applying a map and filter operator to the returned rows.
*/
-export function tsv(
+export function tsv(
url: string,
init: RequestInit,
- row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow | undefined | null
+ row: (rawRow: DSVRowString, index: number, columns: Columns[]) => ParsedRow | undefined | null
): Promise>;
/**
diff --git a/types/distributions/distributions-tests.ts b/types/distributions/distributions-tests.ts
new file mode 100644
index 0000000000..04cb1b65bb
--- /dev/null
+++ b/types/distributions/distributions-tests.ts
@@ -0,0 +1,17 @@
+import * as distributions from 'distributions';
+
+const normal = distributions.Normal();
+normal.cdf(0);
+normal.pdf(0);
+normal.inv(0);
+normal.mean();
+normal.median();
+normal.variance();
+
+const uniform = distributions.Uniform();
+uniform.cdf(0);
+uniform.pdf(0);
+uniform.inv(0);
+uniform.mean();
+uniform.median();
+uniform.variance();
diff --git a/types/distributions/index.d.ts b/types/distributions/index.d.ts
new file mode 100644
index 0000000000..cdfbc93c6b
--- /dev/null
+++ b/types/distributions/index.d.ts
@@ -0,0 +1,18 @@
+// Type definitions for distributions 2.0
+// Project: https://github.com/AndreasMadsen/distributions
+// Definitions by: Marco Lanaro
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+export function Normal(mean?: number, sd?: number): Distribution;
+export function Studentt(df: number): Distribution;
+export function Uniform(a?: number, b?: number): Distribution;
+export function Binomial(properbility: number, size: number): Distribution;
+
+export interface Distribution {
+ pdf: (x: number) => number;
+ cdf: (x: number) => number;
+ inv: (p: number) => number;
+ mean: () => number;
+ median: () => number;
+ variance: () => number;
+}
diff --git a/types/distributions/tsconfig.json b/types/distributions/tsconfig.json
new file mode 100644
index 0000000000..995b1007ef
--- /dev/null
+++ b/types/distributions/tsconfig.json
@@ -0,0 +1,24 @@
+{
+ "compilerOptions": {
+ "module": "commonjs",
+ "lib": [
+ "es6"
+ ],
+ "noImplicitAny": true,
+ "noImplicitThis": true,
+ "strictNullChecks": true,
+ "strictFunctionTypes": true,
+ "esModuleInterop": true,
+ "baseUrl": "../",
+ "typeRoots": [
+ "../"
+ ],
+ "types": [],
+ "noEmit": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "files": [
+ "index.d.ts",
+ "distributions-tests.ts"
+ ]
+}
diff --git a/types/distributions/tslint.json b/types/distributions/tslint.json
new file mode 100644
index 0000000000..3db14f85ea
--- /dev/null
+++ b/types/distributions/tslint.json
@@ -0,0 +1 @@
+{ "extends": "dtslint/dt.json" }
diff --git a/types/draft-js/draft-js-tests.tsx b/types/draft-js/draft-js-tests.tsx
index c0c64256fd..2375da74d4 100644
--- a/types/draft-js/draft-js-tests.tsx
+++ b/types/draft-js/draft-js-tests.tsx
@@ -315,6 +315,7 @@ ReactDOM.render(
const editorState = EditorState.createEmpty();
const contentState = editorState.getCurrentContent();
+const entityMap = contentState.getEntityMap();
const rawContentState: RawDraftContentState = convertToRaw(contentState);
rawContentState.blocks.forEach((block: RawDraftContentBlock) => {
diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts
index 4f2c34dd3a..4c00e7598f 100644
--- a/types/draft-js/index.d.ts
+++ b/types/draft-js/index.d.ts
@@ -9,6 +9,7 @@
// Santiago Vilar
// Ulf Schwekendiek
// Pablo Varela
+// Claudio Procida
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
@@ -754,6 +755,7 @@ declare namespace Draft {
createEntity(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): ContentState;
getEntity(key: string): EntityInstance;
+ getEntityMap(): any;
getLastCreatedEntityKey(): string;
mergeEntityData(key: string, toMerge: { [key: string]: any }): ContentState;
replaceEntityData(key: string, toMerge: { [key: string]: any }): ContentState;
diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx
index 57e028e8bf..481c1b27c4 100644
--- a/types/expo/expo-tests.tsx
+++ b/types/expo/expo-tests.tsx
@@ -47,6 +47,7 @@ import {
Region,
registerRootComponent,
ScreenOrientation,
+ SecureStore,
Svg,
Updates
} from 'expo';
@@ -484,6 +485,30 @@ async () => {
isString(queryParams2['y'] || '');
};
+// #region securestore
+async () => {
+ await SecureStore.setItemAsync('some-key', 'some-val', {
+ keychainService: "some-service",
+ keychainAccessible: SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
+ });
+ const result = await SecureStore.getItemAsync('some-key', { keychainService: "some-service" });
+ if (result != null) {
+ result.slice() === 'some-val';
+ }
+ await SecureStore.deleteItemAsync('some-key', { keychainService: "some-service" });
+};
+
+const allSecureStoreKeychainAccessibleValues: number[] = [
+ SecureStore.WHEN_UNLOCKED,
+ SecureStore.AFTER_FIRST_UNLOCK,
+ SecureStore.ALWAYS,
+ SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY,
+ SecureStore.WHEN_PASSCODE_SET_THIS_DEVICE_ONLY,
+ SecureStore.AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY,
+ SecureStore.ALWAYS_THIS_DEVICE_ONLY,
+];
+// #endregion
+
() => (