【问题标题】:Describe only shape of an object in typescript, but ignore the types在打字稿中仅描述对象的形状,但忽略类型
【发布时间】:2016-10-31 05:39:57
【问题描述】:

我想在打字稿中描述以下对象形状,但我想忽略字段的类型。

interface TestInterface {
  TestOne?: string;
  TestTwo?: number;
  TestThree?: boolean;
}

我的想法是用以下方式来描述它:

type Shape = { [fieldName: string]: any };

type ShapeType<TShape extends Shape> = TShape;

var test: ShapeType<TestInterface> = {
  TestThree: "asdf",
}

它应该抱怨这样的事情:

var test: ShapeType<TestInterface> = {
    TestThree: "asdf",
    TestFour: "123",
}

如果我将“asdf”类型转换为任何它可以工作。有没有办法以不需要强制转换的方式来描述这一点?

编辑:其背后的想法是具有通常用于数据交换但在特殊场合将用于元数据的形状。在这些情况下,我只关心结构,而不关心类型(至少现在 - 想法是将形状的类型更改为另一种给定类型)。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    作为一个概念,我没有看到将某事声明为 boolean 并将其分配为 string... 的优势... em>

    但我们可以这样调整:

    //type ShapeType<TShape extends Shape> = TShape;
    interface Shape { [fieldName: string]: any };
    
    // now, TestInterface also contains [fieldName: string]
    interface TestInterface extends Shape {
      TestOne?: string;
      TestTwo?: number;
      TestThree?: boolean;
    }
    
    
    type ShapeType<TShape extends Shape> = TShape;
    
    // BTW - why we declared TestsThree to be boolean
    // if we assign it to string... that would hardly help
    var test: ShapeType<TestInterface> = {
        TestsThree: "asdf",
    }
    

    或者,如果我们不想让 Shape 成为界面,

    // we have to do this explicitly [fieldName: string]
    interface TestInterface {
      [fieldName: string]: any 
      TestOne?: string;
      TestTwo?: number;
      TestThree?: boolean;
    }
    
    type Shape = { [fieldName: string]: any };
    
    type ShapeType<TShape extends Shape> = TShape;
    
    var test: ShapeType<TestInterface> = {
        TestsThree: "asdf",
    }
    

    这两种方法都可以,但又一次......为什么我们要定义 TestThree?: boolean; 然后将其分配为TestsThree: "asdf",

    【讨论】:

    • 关于原因:通常应该使用形状来交换数据,但我也想将元数据放在这些字段上。所以出于这个原因,我想重用这个形状。
    • 解决方案似乎有一个问题,它允许添加新字段,如“TestFour”而不会抱怨。
    【解决方案2】:

    这是很久以前制作的,但我遇到了类似的问题。您似乎想要一个具有相同属性的对象的类型,但类型为 any 而不是它们的任何类型。

    type ShapeType<T> = { [key in keyof T]?: any };
    
    //fine
    const test1: ShapeType<TestInterface> = {
        TestsThree: "asdf",
    }
    //error "TestFour" is not a valid property
    const test2: ShapeType<TestInterface> = {
        TestThree: "asdf",
        TestFour: "123",
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2022-08-23
      • 2014-02-11
      • 1970-01-01
      • 2018-05-16
      • 2020-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多