typescript

typescript Тип как один из ключей, именно свойств перечислимого типа (Enum). Пример определения

Вот так можно определить тип keyOfMyType, который означает "является ключом енама MyType":

export enum MyType {
  ONE = 'r1',
  TWO = 'p2',
  THREE = 'i3',
}

export type keyOfMyType = keyof typeof MyType;

typescript Object is possibly 'null' -- react useEffect() Ошибка

Не работает даже для:


  React.useEffect(() => {

    if (inputRef !== null) {
      inputRef.current.selectionStart = position;
      inputRef.current.selectionEnd = position;
    }

  }, [position])

--связано с тем, как мы объявляем ссылку, быстрым решением может быть:

const inputRef: any = React.useRef<HTMLInputElement>(null);

typescript fake event Пользовательский объект События совместимый с обычными событиями AS

С помощью утверждения типа (as) можно убедить TS, что ваш объект является полноценным событием, напр. пример конструктора такого события для React:

Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2015' or later

Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to 'es2015' or later.

В ответ на команду:

npx tsc

Решение

В tsconfig.json добавим (в корень объекта конфигурации):

    "lib": [
      "es2015"
    ]

typescript Добавить index.d.ts для собственного пакета библиотеки

could not find declaration file for module

Чтобы решить эту проблему надо создать файл напр. с имененм index.d.ts в корне директории, содержащей пакет.

При этом чтобы ошибка пришла, возможно, придется полностью перезапуска сборщик (напр. командой yarn start)

Официальная документация: https://www.typescriptlang.org/docs/hand...

The type 'readonly ....' is 'readonly' and cannot be assigned to the mutable type Ошибка

Проблема

The type 'readonly {....}[]' is 'readonly' and cannot be assigned to the mutable type

Возникает для кода вида:

let deliveryTypes = [
    { value: 1, label: 'Без доставки'},
    { value: 2, label: 'Страна'},
    { value: 3, label: 'Город'},
];

deliveryTypes = Object.freeze(deliveryTypes);

export { deliveryTypes };

Причина

Полное сообщение об ошибке в моем случае выглядит так:

typescript react children Как указать тип

Можно так:

import React from "react";

type ModalWindowPropsType = {
    children: React.ReactNode,
}

export default function ModalWindow(props: ModalWindowPropsType) {

    return (
        <>
            {props.children}
        </>
    );
}

typescript Преобразование, сужение string[] | string к типу string. Переход от массива к единственному элементу

Проблема

Type 'string | string[] | null' is not assignable to type 'string | null'.
Type 'string[]' is not assignable to type 'string'. TS2322

Есть код:

const params = queryString.parse(history.location.search);

    let initFilterValue: string | null = null;

    if ((typeof params[filterParamName] === 'string')) {
      initFilterValue = params[filterParamName]; // ошибка
    }

При этом типы для queryString.parse() определены так:

Pages

Subscribe to RSS - typescript