2017-08-07 42 views
1

我:指定爲聯合在打字稿

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'. 

我該如何解決這個問題?

+5

注意這是一個*路口*類型,而不是聯合類型(見https://www.typescriptlang.org/docs/handbook/advanced-types.html)。如果它是一個聯合類型('MetaData | Data'),那麼你可以確定,但是你不能在給定它們的定義的情況下使它成爲'MetaData' *和*'Data'的東西(因爲'date'屬性不能同時是'數字「和」日期「)。 – jonrsharpe

+2

無法在TypeScript中描述您想要的內容。索引類型'{[key:string]:number}'意味着每個屬性都必須有'數字'類型,沒有規定類似的東西'但是如果屬性名稱是'日期'它必須是'日期' ,而不是'號碼'「 – artem

回答

0

如果我們想要分配到一個聯合類型,那麼我們需要首先創建一個聯合類型。在你的問題中,你正在創建一個交集類型。

  • 聯合類型使用|運算符並表示「可以是幾種類型之一的值」。
  • 相交類型使用&運算符並將「多個類型合併爲一個」。

一旦我們有一個聯合類型,我們使用它所代表的幾種類型之一來分配它。

這是an example union type assignment in the TypeScript Playground

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