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

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

How to create default type in an atom using typescript?

问题

我正在尝试为一个对象创建一个原子。在原子的默认部分下,我收到以下错误:类型“{}”无法分配给类型“Country | RecoilValue<Country> | Promise<Country> | Loadable<Country> | WrappedValue<Country>”。
属性“[WrappedValue_OPAQUE]”在类型“{}”中丢失,但在类型“WrappedValue<Country>”中是必需的。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-2.html
匿名

发表评论

匿名网友

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

确定