[英]typescript typeof with union or generic
我是 typescript 的新手,并尝试了解如何从 typeof 制作类型,但存在问题。
假设我有 const filter
export const filter = {
filters: {
name: {value: '' , matchMode: ''}
}
}
然后我使用typeof
从const filter
制作FilterType
type FilterType = typeof filter
然后我创建类型为FilterType
的const myFilter
export const myFilter: FilterType = {
filters: {name:{value: 'myValue' , // how to make possible to accept number too?
matchMode: 'contains'}} // how to limit matchMode to accept only values 'contain' or 'eq'
}
如果value
和matchMode
是一个字符串,那么一切都很好,但如果是一个密码,它就不起作用,或者我想预定义matchMode
并且只有在 value 是contain
或 'eq' 时才访问
我怎么能做到这一点? 我想它可以用 Generic 来完成,但是怎么做呢?
您可以预先为您的属性提供额外的类型:
type Name = {
value: string | number
matchMode: 'contains' | 'eq'
}
const name_: Name = {
value: 2,
matchMode: 'contains'
}
const filter = {
filters: {
name: name_,
}
}
type FilterType = typeof filter
const myFilter: FilterType = {
filters: {
name: {
value: 2, // ok
matchMode: 'not contains' // expected error
}
}
}
像这样先定义一个类型
interface FilterType {
filters: {
name: {
value: string | number;
matchMode: 'contain'|'eq'
}
}
}
接着
export const myFilter: FilterType = {
filters: {
name:{
value: 'myValue', // string or number
matchMode: 'contains' // string or number
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.