【问题标题】:Specifying the type of the value in an object literal in Typescript?在 Typescript 的对象文字中指定值的类型?
【发布时间】:2018-06-22 22:06:32
【问题描述】:

这与Type definition in object literal in TypeScript 的问题不同

我有一个接受任何对象作为其属性之一的接口:

interface MyType {
  /* ... */
  options: any;
}

虽然options 属性可以是任何东西,但有时我想指定某些类型。我不想使用 'as' 关键字,因为我不想强制它(如果我缺少属性,我想看到错误)。

这是我可以做到的一种方法:

interface MyTypeOptions {
  hasName: boolean;
  hasValue: boolean;
}

// Declare the options separately just so we can specify a type
const options: MyTypeOptions = {
  hasName: false,
  hasValue: true
};

const myType: MyType = {
  /* ... */
  options
}

但是有没有办法在不使用类型断言的情况下将选项内联在 myType 对象文字中?换句话说,我想这样做:

const myType: MyType = {
  /* ... */
  // I want to type-check that the following value is of type MyTypeOptions
  options: {
    hasName: false,
    hasValue: true
  } 
}

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您正在寻找泛型。您可以将MyType 设为泛型并将MyTypeOptions 指定为MyType 的类型参数

    interface MyTypeOptions {
        hasName: boolean;
        hasValue: boolean;
    }
    
    // Declare the options separately just so we can specify a type
    const options: MyTypeOptions = {
        hasName: false,
        hasValue: true
    }
    
    // We specify any as the default to T so we can also use MyType without a type parameter
    interface MyType<T = any> {
        /* ... */
        options: T;
    }
    const myType: MyType<MyTypeOptions> = {
        options: {
            hasName: false,
            hasValue: true
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2016-12-02
      • 1970-01-01
      • 2022-10-12
      • 2019-05-08
      • 2020-06-21
      相关资源
      最近更新 更多