【问题标题】:TypeScript provide default values for missing keys of a TypeTypeScript 为类型的缺失键提供默认值
【发布时间】:2020-10-07 00:50:31
【问题描述】:

可能有一个非常明显的答案,但是如何做到以下几点:

type testStatus = {
    foo: boolean;
    bar: boolean;
    baz: boolean;
}

const makeDefaults = (o: Partial<testStatus>) => {
   const keys = // array of `testStatus` keys?
   keys.forEach(k => !(k in o) && (o[k] = false)) // provide a default value for missing keys
   return o
}

const obj: Partial<testStatus> = { foo: true, bar: false } 

const defaultedObj = makeDefaults(obj) // { foo: true, bar: false, baz: false }

基本上是从一个 Type 中检索所有的键,然后循环遍历?

【问题讨论】:

标签: typescript


【解决方案1】:

类型仅在编译时存在,因此您尝试执行的确切操作是不可能的。

一个更简单的选择是这样的

type TestStatus = {
    foo: boolean;
    bar: boolean;
    baz: boolean;
}

const defaultTestStatus: TestStatus = {
    foo: false,
    bar: false,
    baz: false
}


const merge = (partialStatus: Partial<TestStatus>): TestStatus => ({
    ...defaultTestStatus,
    ...partialStatus
})

【讨论】:

    【解决方案2】:

    您无法从类型中获取键作为值,因为类型在运行时不存在。如果 type 很简单,并且所有键的值类型都与示例相同 - 您可以先创建一个键数组,然后从中创建类型:

    const KEYS = ['foo', 'bar', 'baz'] as const;
    
    type testStatus = { [K in typeof KEYS[number]]: boolean };
    
    const makeDefaults = (o: Partial<testStatus>) => {
        KEYS.forEach(k => !(k in o) && (o[k] = false))
        return o
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-09
      • 2019-01-02
      • 2020-09-03
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多