如何在 TypeScript 中使用默认类型创建一个原子?

huangapple go评论49阅读模式
英文:

How to create default type in an atom using typescript?

问题

我试图为一个对象创建一个原子。在原子下默认出现以下错误:类型'{}'无法分配给类型'Country | RecoilValue | Promise | Loadable | WrappedValue'。
属性'[WrappedValue_OPAQUE]'在类型'{}'中丢失,但在类型'WrappedValue'中是必需的。ts(2322)
我应该如何修复这个问题?我是TypeScript的新手。

export interface Country {
  capital: string;
  continents: string;
}

import { Country } from "../types/country";
import { atom } from "recoil";

export const countryAtom = atom<Country>({
  key: "countryAtom",
  default: {},
});

(注意:这是您提供的文本的翻译,没有其他内容。)

英文:

I am trying to create an atom for an object. I get the following error under default in the atom: Type '{}' is not assignable to type 'Country | RecoilValue<Country> | Promise<Country> | Loadable<Country> | WrappedValue<Country>'.
Property '[WrappedValue_OPAQUE]' is missing in type '{}' but required in type 'WrappedValue<Country>'.ts(2322)
How can I fix this? I am new to typescript.

export interface Country {
  capital: string;
  continents: string;
}
import { Country } from &quot;../types/country&quot;;
import { atom } from &quot;recoil&quot;;

export const countryAtom = atom&lt;Country&gt;({
  key: &quot;countryAtom&quot;,
  default: {},
});

答案1

得分: 1

你可以在创建原子时指定类型:

export interface Country {
  captial: string;
  continets: string;
}

export const countryAtom = atom<Country>({
  key: "countryAtom",
  default: {
    captial: "example string 1",
    continets: "example string 2",
  }
});
英文:

You can specify the type during the atom creation:

export interface Country {
  captial: string;
  continets: string;
}

export const countryAtom = atom&lt;Country&gt;({
  key: &quot;countryAtom&quot;,
  default: {
    captial: &quot;example string 1&quot;,
    continets: &quot;example string 2&quot;,
  }
});

huangapple
  • 本文由 发表于 2023年3月21日 01:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793670-3.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定