letstr: string = 'abc';
str = 'def'; // no errors, string type can have any value
而字符串字面量类型是一个具有特定值的字符串类型。
letstr: 'abc' = 'abc';
str = 'def'; // Type '"def"' is not assignable to type '"abc"'.
通常情况下,我们将它与联合类型一起使用,用来确定你可以传递给函数、数组、对象的字符串取值的列表。
functioneatSomething(food: 'sushi' | 'ramen') {}
eatSomething('sushi');
eatSomething('ramen');
eatSomething('pencil'); // Argument of type '"pencil"' is not assignable to parameter of type '"sushi" | "ramen"'.letfood: Array<'sushi' | 'ramen'> = ['sushi'];
food.push('pencil'); // Argument of type '"pencil"' is not assignable to parameter of type '"sushi" | "ramen"'.letobject: { food: 'sushi' | 'ramen' };
object = { food: 'sushi' };
object = { food: 'pencil' }; // Type '"pencil"' is not assignable to type '"sushi" | "ramen"'.
const a = 'a';
const b = 'b';
// In JavaScript, you can build a new string// with template literalsconst c = `${a}${b}`; // 'a b'type A = 'a';
type B = 'b';
// In TypeScript, you can build a new string literal type// with template literals too!type C = `${A}${B}`; // 'a b'
typeCollection<X> = X extends'arr' ? number[] : Set<number>;
type A = Collection<'arr'>; // number[]// If you pass in something other than 'arr'type B = Collection<'foo'>; // Set<number>
你使用extends关键字用来测试X的类型是否可以被分配给arr类型,并使用条件运算符(condition ? a : b)来确定测试成立的类型。
// Here you are testing whether X extends `() => ???`// and let TypeScript to infer the `???` part// TypeScript will define a new type called// `Value` for the inferred typetypeGetReturnValue<X> = X extends () => infer Value ? Value : never;
// Here we inferred that `Value` is type `string`type A = GetReturnValue<() =>string>;
// Here we inferred that `Value` is type `number`type B = GetReturnValue<() =>number>;
// return string when passed string[]functionfirstElement(arr: string[]): string;
// return number when passed number[]functionfirstElement(arr: number[]): number;
// then the actual implementationfunctionfirstElement(arr) {
return arr[0];
conststring = firstElement(['a', 'b', 'c']);
// Define type parameter `Item` and describe argument and return type in terms of `Item`function firstElement<Item>(arr: Item[]): Item | undefined {
return arr[0];
// `Item` can only be of `string` or `number`function firstElement<Itemextendsstring | number>(arr: Item[]): Item | undefined {
return arr[0];
constnumber = firstElement([1, 3, 5]);
const obj = firstElement([{ a: 1 }]); // Type '{ a: number; }' is not assignable to type 'string | number'.