简体   繁体   English

如何通过 TypeScript 中的参数 object 形状重载 function?

[英]How to overload function by argument object shape in TypeScript?

Suppose I want to check the string's length, in 2 ways (fixed or range):假设我想以2 种方式(固定或范围)检查字符串的长度:

/* Fixed check */
check('abc', {length: 1}); // false
check('abc', {length: 3}); // true

/* Range check */
check('xyz', {minLength: 5, maxLength: 10}); // false
check('xyz', {minLength: 1, maxLength: 10}); // true
check('xyz', {minLength: 3, maxLength: 3}); // true

I first declared the 2 interfaces as follows:我首先声明了 2 个接口,如下所示:

interface StringFixed {
  length: number;
}

interface StringRange {
  minLength: number;
  maxLength: number;
}

Then I try to write the function:然后我尝试写function:

function check(value: string, schema: StringFixed): boolean;
function check(value: string, schema: StringRange): boolean;
function check(value: string, schema: StringFixed | StringRange): boolean {
  if (typeof schema.length !== 'undefined') { // ERROR
    // Fixed check
  } else {
    // Range check
  }
}

But now the TypeScript reports the ERROR in the first line of the function:但是现在 TypeScript 在 function 的第一行报告错误:

TS2339: Property 'length' does not exist on type 'StringFix | StringRange'

My question is how to do this in TypeScript?我的问题是如何在 TypeScript 中做到这一点?

You're so close.你是如此接近。 :-) You're asking for the type of the value of a property that you expect to be there ( typeof schema.length ). :-) 您正在询问您希望存在的属性值的类型( typeof schema.length )。 To implement a type guard , you want to ask if the property is there:要实现类型保护,您需要询问该属性是否存在:

if ("length" in schema) {
    // Fixed check
} else {
    // Range check
}

Working copy on the TypeScript playground . TypeScript 操场上的工作副本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM