我意识到这可能违背了TypeScript的哲学,但我想我还是会问的。
是否有可能在编译时将类型文本转换为字符串文本?
例如,我可以在不重复的情况下将"AnotherString"分配给str2吗?
// object to type, no problem
const obj = "SomeString";
let str1: typeof obj = obj;
// type into obj: ?
type SomeType = "AnotherString";
const str2: SomeType = valueof SomeType
在剃须刀区
@{
Like This
}
我需要能够调用c#函数
static T Cast<T>(object o)
{
return (T)o;
}
以便动态地强制转换对象。我如何访问这些代码?
我希望能做到这一点
someObject = Cast<someType>(someObject);
编辑
我正在尝试实现一个通用视图模型。
以下是模型:
public class GenericVM<TEntity> where TEntity : class
{
public List<TEntity> Entities { get;
是否有方法将字符串映射到TypeScript中匹配的模板文字类型?
下面是一个例子:
type SomeType<T> = {
[P in keyof T as `as${Capitalize<string & P>}`]: number;
};
这应该将x的每个属性都转换为T,并使其成为属性asX。
但是现在我想取一个像foo这样的属性名,并以TypeScript可以检测到的方式将其转换为asFoo。
我希望能够做到这一点:
interface I {
foo: number;
bar: number;
}
const obj: SomeType
我有一些打字代码:
const wrapField = <T extends { value: string }>(fieldValue: string): T => ({
value: fieldValue,
});
Typescript给我一个错误:
'{ value: string; }' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint
我有一个第三方设计差的图书馆,我必须使用。
它有各种类型,我们称之为SomeType1,SomeType2等。
这些类型中没有一个共享公共基类,但它们都具有一个具有不同返回类型的名为Value的属性。
我想要做的就是能够在这个类中找到一个新的类型,这样我就可以调用someType1Instance.Value和someType2Instance.Value,而不关心它是什么类型,也不关心返回类型是什么(我可以使用object)。
所以我的代码是:
public interface ISomeType<V>
{
V Value {get; set;}
}
public inte
如何在typescript中传递所需参数的条件类型参数? type SomeType = string | string[]
const a: SomeType = "some string"
function person (param: string) {
}
person(a) // gives error in lint => Type 'string[]' cannot be used as an index type
当我在Typescript中尝试这样的东西时... interface SomeType {
size: 'sm' | 'md' | 'lg';
other: any;
}
let size: Pick<SomeType, 'size'> = 'sm'; 我得到了这个错误。这是预期的错误吗? Type '"sm"' is not assignable to type 'Pick<SomeType, "size">'
我编写了一个以对象作为参数的管道:
@Pipe({name: "myPipe"})
export class MyPipe implements PipeTransform {
transform (value: string, options: any): string {
// do stuff with value and options here
}
}
当我为options使用变量时,它工作得很好。
<!-- this works fine -->
{{someString | myPipe: someObject}}
但是
在Typescript中,我想这样做:
interface SomeType {
name: string
}
useState([]:SomeType[]); // This creates an empty array of SomeType inline & calls a function called useState
甚至是
function getArrayOfSomeType():SomeType[] {
return []:SomeType[];
}
其他情况可能涉及相同的概念,但带有映射/字典:
// Maybe there is a better way t
我在TypeScript 3.2.2和strict: true上。
我无法键入具有一组动态定义键的普通对象,但所有这些键都有一个有保证的非空值类型。
[TypeScript游乐场示例]()
// Will assume any property access has type T
interface Object<T> {
[key: string]: T;
}
// Will assume Object.values() could be undefined
interface Object<T> {
[key: string]: T | undef
如果我们有一个带有一些ADT类型类,如下所示
trait MyRule {
type T
class ResourceIdType[A](val value: A)
case class StringResourceIdType(override val value: String) extends ResourceIdType(value)
case class ListResourceIdType(override val value: List[Int]) extends ResourceIdType(value)
def resourceType(rtm: T)