Код: Выделить всё
.tsКод: Выделить всё
.jsУ нас есть владелец состояния класса , экземпляры которых содержат данные, описанные генерическим состоянием . Данные могут быть предоставлены на создании экземпляров или позже. br />
Код: Выделить всё
// state.ts
type StateHolderOptions = {};
class StateHolder {
value?: State;
constructor(
initialValue?: State,
options: StateHolderOptions = {}
) {
if (initialValue !== undefined) {
this.value = initialValue;
}
}
}
type MyState = { data: string };
const state = new StateHolder(undefined, {});
< /code>
Вот тот же код, что и мы преобразовали его в js: < /p>
// state.js
/**
* @typedef {object} StateHolderOptions
*/
/**
* @template State
*/
class StateHolder {
/**
* @type {State | undefined}
*/
value;
/**
* @param {State} [initialValue]
* @param {StateHolderOptions} [options] - Unused
*/
constructor(initialValue, options = {}) {
if (initialValue !== undefined) {
this.value = initialValue;
}
}
}
/**
* @typedef {{ data: string }} MyState
*/
const state = /** @type {StateHolder} */(new StateHolder(undefined, {}));
< /code>
Мы думали, что JS и TS были точно эквивалентны. Тем не менее, в версии JS окончательная строка Const compate Код: Выделить всё
Conversion of type 'StateHolder' to type 'StateHolder' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
Type 'undefined' is not comparable to type 'MyState'.
< /code>
Мы не получаем ошибок типа, если мы сделаем это, но это очень многослов, поэтому было бы неплохо избежать: < /p>
const state = new StateHolder(/** @type {MyState} */(/** @type {unknown} */(undefined)), {});
Подробнее здесь: https://stackoverflow.com/questions/794 ... t-not-type
Мобильная версия