2017-01-22 84 views
3

有沒有辦法強制打字稿更嚴格的類型檢查,直到每個別名檢查?Typescript嚴格別名檢查

我想實現的是定義類型,如:

type kilograms = number; 
type kilometers = number; 
type kilogramsPerKilometer = number; 

而且可以肯定的是我不把錯誤類型值到一個變量如:

let x: kilograms = 123; 
let y: kilometers = 256; 
let z: kilogramsPerKilometer = x/y; // Will popup an error here saying that types are incompatible 

在這種情況下,需要顯式類型轉換:

let x: kilograms = 123; 
let y: kilometers = 256; 
let z: kilogramsPerKilometer = <number>x/<number>y; // Will downcast `kilograms` and `kilometers` types to `number` and then up-cast types to `kilogramsPerKilometer` 

回答

0

嘗試做這樣的:

type kilograms = number; 
type kilometers = number; 
type kilogramsPerKilometer = number; 

function kilosPerKiloms(x: kilograms, y: kilometers): kilogramsPerKilometer { 
    return x/y; 
} 

let x: kilograms = 123; 
let y: kilometers = 256; 
let z: kilogramsPerKilometer = kilosPerKiloms(x, y); 
+0

這種方法如何執行嚴格的別名檢查? – Lu4

1

有在TS(還)沒有正常打字https://github.com/Microsoft/TypeScript/issues/202

這是承認溶液(使用判別工會):

interface kilograms { 
    kind: "kilograms"; 
    value: number; 
} 

interface kilometers { 
    kind: "kilometers"; 
    value: number; 
} 

function kilosPerKiloms(x: kilograms, y: kilometers): kilogramsPerKilometer { 
    return x.value/y.value; 
} 

const x = { kind: "kilograms", value: 123 }; 
const y = { kind: "kilometers", value: 256 }; 
const z = kilosPerKiloms(x, y); 
// const z = kilosPerKiloms(y, x); // => error 

更多的信息有:

https://www.typescriptlang.org/docs/handbook/advanced-types.html

https://basarat.gitbooks.io/typescript/content/docs/types/discriminated-unions.html