0

我正在寻找一种方法使下面的代码失败。

当我创建这些InOut类型时,我希望将任何字符串传递到usage必须转换为In. 这可能吗?

type In = string;
type Out = string;

const usage = (x: In): Out => 'meow';

usage('hi');
4

1 回答 1

0

我认为为此我们可能必须创建自己的类型而不是使用字符串类型。ts 中的 type 关键字只是所用类型的别名,更多细节在这里 -

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.10

所以上面的代码是一样的:

const usage = (x: string): string=> 'meow';

如果您正在寻找某种方法,该方法采用具有字符串属性的对象;

type In = {text:string};
type Out = string;

const usage = (x: In): Out => 'meow';
const data: In = { text: 'value' };
usage(data);
于 2019-01-04T21:42:00.513 回答