function isString (s: unknown): boolean {
return typeof s === 'string'
}
function toUpperCase (x: unknown) {
if (isString(x)) {
x.toUpperCase() // × Error, Object is of type 'unknown'
}
}
const isString = (s: unknown): s is string => typeof val === 'string'
function toUpperCase (x: unknown) {
if (isString(x)) {
x.toUpperCase()
}
}
// 一
interface Person {
name: string
age: number
}
const sem: Person = { name: 'semlinker', age: 30 }
type Sem = typeof sem // type Sem = Person
// 二
const kakuqo = {
name: 'kakuqo',
age: 30,
address: {
province: '广东'
}
}
type Kakuqo = typeof kakuqo
/*
type Kakuqo = {
name: string;
age: number;
address: {
province: string;
city: string;
};
}
*/
// 三
function toArray (x: number): Array<number> {
return [x]
}
type Func = typeof toArray // -> (x: number) => number[]
扩展
typeof 和 keyof 操作符
typeof 操作符可以用来获取一个变量或对象的类型。
keyof 操作符可以用于获取某种类型的所有键,其返回类型是联合类型。
它们可以结合一起使用:
示例
typescript复制代码
const COLORS = {
red: 'red',
blue: 'blue'
}
// 首先通过typeof操作符获取Colors变量的类型,然后通过keyof操作符获取该类型的所有键,
// 即字符串字面量联合类型 'red' | 'blue'
type Colors = keyof typeof COLORS
let color: Colors
color = 'red' // √
color = 'blue' // √
color = 'yellow' // × Type '"yellow"' is not assignable to type '"red" | "blue"'.