如何在初始化对象之前设置对象的类型?



我有一个传递给组件的sprites对象。最初它是一个空对象,但它的父组件调用一个rest端点来填充这个sprites对象。处理这个问题的最佳方法是什么?

我需要使sprites道具可选吗?下面是代码。。。

type SpriteProps = {
sprites: {}
name: string
loading: boolean
}
const Sprite = ({ sprites = {}, name, loading }: SpriteProps) => {

谢谢!!

你想要的是不可能的。当您根据需要在接口上定义类型时(即,它没有?(,意味着必须定义它:

type SpriteProps = {
sprites: {}
name: string
loading: boolean
}
// This is incorrect
// SpriteProps is saying all properties are required
// But right now `prop.name` for example is not
const prop: SpriteProps = {};

如果在定义了类型之后必须填充内容,则需要将字段设置为可选字段。你可以做这两项中的任何一项:

type SpriteProps = {
sprites?: {}
name?: string
loading?: boolean
}
// This is fine now
const prop: SpriteProps = {};

type SpriteProps = {
sprites: {}
name: string
loading: boolean
}
// This is fine now
const prop: Partial<SpriteProps> = {};

另一种选择是为以下字段创建一个空值对象:

type SpriteProps = {
sprites: {}
name: string
loading: boolean
}
// This is fine now
const prop: Partial<SpriteProps> = {
sprites: {},
name: '',
loading: true,
};

最新更新