仅描述打字稿中对象的形状,但忽略类型

时间:2016-10-31 05:39:57

标签: typescript

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

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”强制转换为任何可行的方式。有没有办法用不需要铸造的方式来描述它?

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

1 个答案:

答案 0 :(得分:2)

作为一个概念,我没有看到声明某些内容 boolean 并将其指定为 string 的优势。 ..

但我们可以像这样调整它:

//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",