在TypeScript接口中描述属性对象

问题描述 投票:5回答:3

我想描述一些嵌套对象的接口。如何在不为嵌套对象创建接口的情况下执行此操作?

interface ISome {
  strProp:string;
  complexProp:{
    someStrKeyWhichIsDynamic:{
      value:string;
      optValue?:string;
    }
  };
}

我也试过了(UPD:实际上还可以)

interface ISome {
  strProp:string;
  complexProp:{
    [someStrKeyWhichIsDynamic:string]:{
      value:string;
      optValue?:string;
    }
  };
}

但是我不能分配像这样的对象

let dynamicStrKey = 'myKey';
  {
   strProp:'str', 
   complexProp:{
     [dynamicStrKey]:{
       value:'something here',
       optValue: 'ok, that too',
    }
  };

变量与ISome类型没有类型断言<ISome>。至少WebStorm将此分配强调为错误。

如何正确描述嵌套对象?

typescript types type-conversion webstorm typescript2.0
3个回答
3
投票

前两个例子没有错。他们都编译得很好,并且意味着他们所说的。

在第三个示例中,您显然希望属性名称为“动态”。但请记住,TS在编译时运行。在编译时,dynamicStrKey还没有价值。因此,尝试将其用作类型定义中的属性名称是没有意义的。您无法使用运行时值定义编译时工件。


3
投票

最后,我认为我的第二个变体是正确的

interface ISome {
  strProp:string;
  complexProp:{
    [someStrKeyWhichIsDynamic:string]:{
      value:string;
      optValue?:string;
    }
  };
}

对于动态密钥,您可以编写[dynamic:string]来指定这里将是一些字符串属性。好像我遇到了与此问题无关的webstorm错误。

顺便说一句,如果你有一些基于字符串的枚举,你可能想使用[key in MyEnum]: {...}而不是[key:string]。这解决了错误:

TS1337索引签名参数类型不能是联合类型。

如果你有一个文字对象,例如const obj = { prop1: 'blah', prop2: 'blahblah' }

您可能希望使用[key in keyof typeof obj]: {...}来描述您的动态密钥只能是'prop1'或'prop2'(或更通用的,来自Object.keys(obj的值))


2
投票

第二部分的代码是支持动态属性。你不能使用最后一个,因为类型没有发出javascript代码。我想你只是喜欢下面的东西,使用泛型代替。更多细节,你可以看到打字稿index types

interface ISome<K extends string> {
    strProp: string;
    complexProp: {
        [P in K]: {
            value: string;
            optValue?: string;
        }
    };
}


let foo: ISome<"foo"> = {
    strProp:"foo",
    complexProp:{
        foo:{
            value:"foo"
        }
    }
};

let bar: ISome<"bar"> = {
    strProp:"bar",
    complexProp:{
        bar:{
            value:"bar",
            optValue:"<optional>"
        }
    }
};

let foobar: ISome<"foo"|"bar"> = {
    strProp:"foo",
    complexProp:{
        foo:{
            value:"foo"
        },
        bar:{
            value:"bar",
            optValue:"<optional>"
        }
    }
};

// interesting things that use with any|never types
let anything:ISome<any|never>={
    strProp:"foo",
    complexProp:{}
};
© www.soinside.com 2019 - 2024. All rights reserved.