rid*_*nsb 8 typescript typescript-typings
如何定义和初始化一个可以为空的对象。
有类型
type Plan = 'plan1' | 'plan1';
interface IPlan {
name: string
}
Run Code Online (Sandbox Code Playgroud)
当我尝试初始化一个空对象时,出现错误
const plans: Record<Plan, Readonly<IPlan> = {}; // **ERROR HERE**
plans.plan1 = {
name: 'Plan #1'
}
Run Code Online (Sandbox Code Playgroud)
类型“{}”中缺少属性“plan1”,但类型“Record<"plan1", Readonly>”中需要属性“plan1”。
只需使用 Partial 实用程序类型:Partial<Type>
type Plan = 'plan1' | 'plan1';
interface IPlan {
name: string
}
const plans: Partial<Record<Plan, IPlan>> = {}; // no error
plans.plan1 = {
name: 'Plan #1'
}
Run Code Online (Sandbox Code Playgroud)
这种方法的缺点是现在界面的所有属性都是可选的。但由于您希望它在没有所需属性的情况下实例化,因此这是唯一的方法。
另一个想法可能是使用 Omit 实用程序类型:Omit<Type, Keys>
interface Plan {
name: string;
}
type IPlan = Omit<Plan , "name">;
const plans: IPlan = {};
Run Code Online (Sandbox Code Playgroud)
因此,您可以在没有所需属性的情况下进行实例化。
你可以这样做:
type Plan = 'plan1' | 'plan2';
interface IPlan {
name: string
}
type PlansRecord = Record<Plan, Readonly<IPlan>>
const plansRecord = {} as PlansRecord
console.log({plansRecord})
Run Code Online (Sandbox Code Playgroud)
输出:
[LOG]: { "plansRecord": {} }
归档时间: |
|
查看次数: |
10523 次 |
最近记录: |