简体   繁体   English

如何在Typescript(Angular)中将类型实现为对象的值

[英]How to implement type to Object's value in Typescript(Angular)

I'd like to implement type to object's value. 我想将类型实现为对象的值。 The problem is that target object has to have another type. 问题在于目标对象必须具有另一种类型。 The object is Angular's Router. 对象是Angular的路由器。

What I want to do is. 我想做的是。

const object: Type = [{ // <-- I have to use Type here.
  otherkey: value,
  data: { // <-- I want to implement type here.
   a: 1,
   b: 'hello'
     }
}]

interface TypeForData {
   a: number;
   b: string;
}
----------------------
// in library's .d.ts file
export declare Type{
  otherkey: ...;
  [data: string]:any;
}[]

I tried these solution. 我尝试了这些解决方案。

  1. extend Type. 扩展类型。
  2. cast value(object). 强制转换值(对象)。

1.extend Type 1.扩展类型

import { Type } from 'somewhere'
interface TypeForData extends Type{
    a: number;
    b: string;
}[]
then implement to variable. but doesn't work well.

2.cast value(object). 2.cast值(对象)。

const object: Type = [{ 
  otherkey: value,
  data: <TypeForData> { 
   a: 1,
   b: 'hello'
     }
}]
but CLI doesn't show error even I assign different type value.

I'm really happy if I could get solution. 如果能得到解决,我真的很高兴。 Thank you. 谢谢。

You can try this. 你可以试试看

interface TypeForData {
   a: number;
   b: string;
}

var someData: TypeForData;

var obj = {
    someData
};

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM