Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 类构造函数可选参数_Typescript - Fatal编程技术网

Typescript 类构造函数可选参数

Typescript 类构造函数可选参数,typescript,Typescript,我希望能够初始化一个有值或无值的类。如果您传递一个值,那么类的所有方法都希望该值作为参数,并且该值将是您通过初始化传递的类型 如果没有传递任何内容,那么方法将不需要任何参数,并且该值将是未定义的 我认为代码将提供更好的示例: class Foo<T = void> { constructor(public type?: T) {} bar = (type: T) => { if (type) { this.type = type; }

我希望能够初始化一个有值或无值的类。如果您传递一个值,那么类的所有方法都希望该值作为参数,并且该值将是您通过初始化传递的类型

如果没有传递任何内容,那么方法将不需要任何参数,并且该值将是未定义的

我认为代码将提供更好的示例:

class Foo<T = void> {
  constructor(public type?: T) {}

  bar = (type: T) => {
    if (type) {
      this.type = type;
    }
  };
}

const fooUndefined = new Foo();

fooUndefined.bar(); // no errors
fooUndefined.type === undefined; // no errors
fooUndefined.bar(1); // expected error, this is ok

const fooNumber = new Foo(0);

fooNumber.type === 1; // no errors, but type is `number | undefined`, this is not ok
fooNumber.type > 0; // unexpected error because type is `number | undefined`, this is not ok

fooNumber.bar(1); // no errors
fooNumber.bar(); // expected error, need to pass number, this is ok
fooNumber.bar('1'); // expected error, strings are not acceptable, this is ok
class-Foo{
构造函数(公共类型?:T){}
条形图=(类型:T)=>{
如果(类型){
this.type=type;
}
};
}
const fooUndefined=新的Foo();
foodUndefined.bar();//没有错误
foodUndefined.type==未定义;//没有错误
foodUndefined.bar(1);//预期错误,这是正常的
const Foo number=新Foo(0);
fooNumber.type==1;//没有错误,但类型为'number | undefined',这不正常
fooNumber.type>0;//意外错误,因为类型为“number | undefined”,这不正常
foodnumber.bar(1);//没有错误
foodNumber.bar();//预期错误,需要传递数字,这是确定的
foodnumber.bar('1');//预期错误,字符串不可接受,这是正常的
因此,
foodumber
示例中的
type
属性的类型是
number |未定义的
。有没有一种方法可以在不显式打字的情况下将其缩小到数字


所有条件参数都得到未定义的SomeType

你可以这样写来绕过它

按数字铸造

fooNumber.type as number > 2
或者告诉typescript,您确信使用它有可用的值!表情

fooNumber.type! > 2 

谢谢你的回答,但这并不能解决问题!可能还有另一种方法来编写类,可能是使用构造函数重载或其他方法,所以您不需要任何类型转换所有问题都来自泛型类型
t=void
,这就是为什么
fooUndefined.bar();//无错误
不会抛出任何错误。如果不抛出,则可以,这是预期的且正确的行为。我想解决的问题是
foodumber.type
属于
number | undefined
类型。以某种方式将其缩小到数字会很好。