在TypeScript中将类型分配给联合类型

3

我有:

interface Data {
    [key: string]: number
}

interface MetaData {
    date: Date
}

export type Datapoint = MetaData & Data

目前为止一切都很好。问题出现在我需要制作其中之一时:

const d: Datapoint = {date: new Date()}

-> error TS2322: Type '{ date: Date; }' is not assignable to type 'Datapoint'.
  Type '{ date: Date; }' is not assignable to type 'Data'.
    Property 'dd' is incompatible with index signature.
      Type 'Date' is not assignable to type 'number'.

我该怎样解决这个问题?

6
请注意这是一个“交叉类型”,而不是联合类型(请参见https://www.typescriptlang.org/docs/handbook/advanced-types.html)。如果它是一个联合类型(`MetaData | Data`),那么你就没问题了,但是根据它们的定义,你不能创建既是“MetaData”又是“Data”的东西(因为“date”属性不能同时是“number”和“Date”)。 - jonrsharpe
2
在 TypeScript 中无法描述您想要的内容。索引类型 { [key: string]: number} 意味着每个属性都必须具有 number 类型,没有任何规定可以像“但如果属性名称是 date,它必须是 Date 而不是 number”这样。 - artem
1个回答

4
如果我们想要分配给联合类型,那么我们首先需要创建一个联合类型。在您的问题中,您正在创建交集类型。
- 联合类型使用 | 运算符,并表示“可以是多种类型之一的值”。 - 交集类型使用 & 运算符,并将“多个类型组合成一个”。
一旦我们拥有了联合类型,就可以使用它所代表的多个类型之一进行分配。
以下是TypeScript Playground中示例联合类型赋值:
```html interface Data { [key: string]: number; }
interface MetaData { date: Date; }
// This creates a union type. type Datapoint = MetaData | Data;
// This assigns to it with the MetaData type. let someMetaData: Datapoint = { date: new Date() };
// This assigns to it with the Data type. let someData: Datapoint = { "foo": 12376, "bar": 11233, "baz": 72343 }; ```
interface Data {
  [key: string]: number;
}

interface MetaData {
  date: Date;
}

// This creates a union type.    
type Datapoint = MetaData | Data; 

// This assigns to it with the MetaData type
let someMetaData: Datapoint = {
  date: new Date()
};

// This assigns to it with the Data type
let someData: Datapoint = {
  "foo": 12376, 
  "bar": 11233, 
  "baz": 72343
};

请参考:

另请参阅:https://www.typescriptlang.org/docs/handbook/advanced-types.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接