打字稿严格别名检查

时间:2017-01-22 11:37:17

标签: typescript typescript2.0

有没有办法强制使用打字稿来进行更严格的类型检查以达到别名检查?

我想要实现的是定义类型,例如:

    config.toolbar_Content =
    [
        ['Undo','Redo','-','PasteText','-','Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink']
    ];

并且确保我不会将错误输入的值放入变量中,例如:

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

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您正在寻找名义上的打字。计划支持未来的TypeScript版本(请参阅Roadmap)。 现在,你必须使用这个: https://basarat.gitbooks.io/typescript/docs/tips/nominalTyping.html

答案 2 :(得分: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);

答案 3 :(得分:0)

不知何故,我在实际找出一个有趣的解决方案时忘记了这个问题。更漂亮,不影响界面,不污染IDE的建议列表。

newnames = df['name'].str.replace(' ', '_', regex=False).tolist()

适用于任何类型