![](/img/trans.png)
[英]How to return strongly typed value from a Map<string, object> method
[英]how to return typed value
我有这个随机化 3 个字符串的函数,但是当我尝试返回该值时,出现此错误
类型 'string' 不能分配给类型 '"DAY" | “GTD” | “GTC”'
我的功能:
export const randomizeTimeinforce = (): 'DAY' | 'GTD' | 'GTC' => {
const timeinforce = ['DAY', 'GTD', 'GTC'];
return timeinforce[Math.floor(Math.random() * 3)];
};
export class MyCoolClass {
public timeinforce: 'DAY' | 'GTD' | 'GTC' = randomizeTimeinforce();
}
您需要添加一个所谓的const 断言,以避免 TS 将您的timeinforce
数组解释为string[]
。 后一种(默认)行为也称为类型扩展,这是您想在此处避免的...
export const randomizeTimeinforce = () => {
const timeinforce = <const>['DAY', 'GTD', 'GTC'];
return timeinforce[Math.floor(Math.random() * 3)];
};
export class MyCoolClass {
public timeinforce = randomizeTimeinforce();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.