无法在 javascript 中“转换”打字稿定义
Posted
技术标签:
【中文标题】无法在 javascript 中“转换”打字稿定义【英文标题】:can't 'convert' typescript definition in javascript 【发布时间】:2021-08-11 07:11:38 【问题描述】:我正在尝试将 this Apollo typescript repository 重写为 javascript。 我尝试学习打字稿,但有一件事叫做“类型转换”或“类型断言”,这让我感到困惑。
让我用代码解释一下:
//cache.tsx
import InMemoryCache, ReactiveVar, makeVar from "@apollo/client";
import Todos from "./models/Todos";
import VisibilityFilter, VisibilityFilters from "./models/VisibilityFilter";
export const cache...
...
...
export const todosVar: ReactiveVar<Todos> = makeVar<Todos>( //how i can 'convert' this type caster value to vanilla js?
todosInitialValue
);
export const visibilityFilterVar = makeVar<VisibilityFilter>( //how i can 'convert' this type caster value to vanilla js?
VisibilityFilters.SHOW_ALL
)
此 cache.tsx 使用的其他 2 个文件是:
//todos.tsx
export interface Todo
text: string;
completed: boolean;
id: number
export type Todos = Todo[];
和
VisibilityFilter.tsx
export type VisibilityFilter =
id: string;
displayName: string;
export const VisibilityFilters: [filter: string]: VisibilityFilter =
SHOW_ALL:
id: "show_all",
displayName: "All"
,
SHOW_COMPLETED:
id: "show_completed",
displayName: "Completed"
,
SHOW_ACTIVE:
id: "show_active",
displayName: "Active"
在这种情况下如何避免 typescript 类型检查,更重要的是,如何正确使用 ReactiveVar 和 makeVar 导入?
【问题讨论】:
【参考方案1】:只需像这样删除泛型:
发件人:
makeVar<Todos>(
收件人:
makeVar(
改变这个:
export const todosVar: ReactiveVar<Todos> = makeVar<Todos>( //how i can 'convert' this type caster value to vanilla js?
todosInitialValue
);
export const visibilityFilterVar = makeVar<VisibilityFilter>( //how i can 'convert' this type caster value to vanilla js?
VisibilityFilters.SHOW_ALL
)
到这里:
export const todosVar = makeVar(todosInitialValue);
export const visibilityFilterVar = makeVar(VisibilityFilters.SHOW_ALL);
如何避免 typescript 检查 - 将扩展名从 .ts 和 .tsx 分别替换为 .js 和 .jsx。
【讨论】:
以上是关于无法在 javascript 中“转换”打字稿定义的主要内容,如果未能解决你的问题,请参考以下文章
在javascript中将数字转换为数组| angular7的打字稿[重复]