简体   繁体   English

用 Record 类型初始化 typescript 中的空 object

[英]Initialize empty object in typescript with Record type

How to define and initialize an object that can be empty.如何定义和初始化一个可以为空的 object。

With types有类型

type Plan = 'plan1' | 'plan1';

interface IPlan {
    name: string
}

When I tried to initialize an empty object, I'm getting an error当我尝试初始化一个空的 object 时,出现错误

const plans: Record<Plan, Readonly<IPlan> = {}; // **ERROR HERE**

plans.plan1 = {
    name: 'Plan #1'
}

Property 'plan1' is missing in type '{}' but required in type 'Record<"plan1", Readonly>'.类型“{}”中缺少属性“plan1”,但类型“Record<"plan1", Readonly>' 中是必需的。

Playgro 游乐场

You could do something like:您可以执行以下操作:

type Plan = 'plan1' | 'plan2';

interface IPlan {
    name: string
}

type PlansRecord = Record<Plan, Readonly<IPlan>>
const plansRecord = {} as PlansRecord

console.log({plansRecord})

Output: [LOG]: { "plansRecord": {} } Output: [LOG]: { "plansRecord": {} }

Demo 演示

Simply use the Partial utility type: Partial<Type>只需使用 Partial 实用程序类型: Partial<Type>

type Plan = 'plan1' | 'plan1';

interface IPlan {
    name: string
}


const plans: Partial<Record<Plan, IPlan>> = {}; // no error

plans.plan1 = {
    name: 'Plan #1'
}

The downside of this approach is that now all the properties of your interface are optional.这种方法的缺点是现在界面的所有属性都是可选的。 But since you want it to instantiate without the required property, that is the only way.但是由于您希望它在没有所需属性的情况下实例化,所以这是唯一的方法。

Playground Link 游乐场链接

Another idea might be using the Omit utility type: Omit<Type, Keys>另一个想法可能是使用 Omit 实用程序类型: Omit<Type, Keys>

interface Plan {
  name: string;
}

type IPlan = Omit<Plan , "name">;

const plans: IPlan = {};

So, again, you can instantiate without the required properties.因此,再次,您可以在没有所需属性的情况下进行实例化。

Playground Link 游乐场链接

Looking atthe documentation for Typescript's Record , it looks like they require a more elaborate object definition:查看 Typescript's Record的文档,看起来他们需要更详细的 object 定义:

const plans: Record<Plan, Readonly<IPlan>> = {plan1: {name: 'foo'}, plan2: {name:'bar'}}

or:或者:

  const plans: Record<Plan, Readonly<IPlan>> = {plan1: {name: 'foo'}}

If you're just trying to create an element with types, you could just use a class or interface with Optional Properties (see here) .如果您只是尝试创建具有类型的元素,则可以使用 class 或与Optional Properties (see here)的接口。 for example:例如:

interface IPlan {
    name?: string;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM